0

I Can't Update my array using methods in Vue.js !

<script>
import Vue from 'vue';
export default {
  data () {
    return {
      from:'',
      to:'',
      places:[]
    }
  },
  methods:{
    searchFrom:function(){
      var autoComplete = new google.maps.places.AutocompleteService();
      autoComplete.getPlacePredictions({input:this.from},function(data){
        this.places=data;
      });
    }
  },
  computed:{

  }
}
</script>

<style>

</style>

This throws an error on console: "Uncaught TypeError: Cannot read property 'places' of undefined"

Melvin George
  • 89
  • 1
  • 1
  • 7

2 Answers2

2

This is because you're not using fat arrows, change the code to:

 methods:{
    searchFrom (){
      var autoComplete = new google.maps.places.AutocompleteService();
      autoComplete.getPlacePredictions({input:this.from}, data => {
        this.places=data;
      });
    }
  },

In more details: when you call autoComplete.getPlacePredictions it uses a callback, and in that callback the this context is changed and is no longer Vue context, so it does not know what this.places is. Fat arrow (=>) takes care of it and makes sure that the context remains the same.

Tomer
  • 17,787
  • 15
  • 78
  • 137
0

I've never had good luck using fat arrows in Vue. The this is not what you expect. Try explicitly assigning this at the start of your searchFrom() method, like this...

 methods:{
    searchFrom (){
      var me = this;
      var autoComplete = new google.maps.places.AutocompleteService();
      autoComplete.getPlacePredictions({me.from}, data => {
        me.places=data;
      });
    }
  }
bbsimonbb
  • 27,056
  • 15
  • 80
  • 110
  • You do't need to do that if you're using an arrow function as they do not create their own execution context. That's OK if you're using normal functions and you can also use `bind`. – craig_h Nov 29 '17 at 11:29