【问题标题】:How to update Array In Vue.js using method? [duplicate]如何使用方法更新 Vue.js 中的数组? [复制]
【发布时间】:2017-11-29 10:25:35
【问题描述】:

我无法使用 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>

这会在控制台上引发错误:“Uncaught TypeError: Cannot read property 'places' of undefined

【问题讨论】:

  • 我正在使用正则表达式@craig_h

标签: javascript ecmascript-6 vue.js


【解决方案1】:

这是因为您没有使用粗箭头,请将代码更改为:

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

更多详情: 当您调用 autoComplete.getPlacePredictions 时,它使用回调,并且在该回调中 this 上下文已更改并且不再是 Vue 上下文,因此它不知道 this.places 是什么。粗箭头 (=>) 负责处理并确保上下文保持不变。

【讨论】:

  • fatman 推荐使用胖箭头。 :-D 你得到了我的选票!
  • @DannyThunder - 哈哈
  • 这解决了我的问题。
  • 太棒了 :) 随时将其标记为答案
【解决方案2】:

我从来没有在 Vue 中使用过粗箭头。这不是你所期望的。尝试在 searchFrom() 方法的开头显式分配this,如下所示...

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

【讨论】:

  • 如果您使用箭头函数,则不需要这样做,因为它们不会创建自己的执行上下文。如果您使用的是普通功能,那没关系,您也可以使用bind
猜你喜欢
  • 2018-04-27
  • 2018-01-25
  • 1970-01-01
  • 2017-06-05
  • 2018-02-05
  • 2019-02-19
  • 2020-05-07
  • 2019-10-18
  • 1970-01-01
相关资源
最近更新 更多