2017-05-14 86 views
2

我使用vueJS編寫項目。我曾與下面的代碼組件:方法在觀察者回調中不是函數vuejs

import ProjectsStore from './../stores/ProjectsStore.js'; 

export default { 
    store: ProjectsStore, 
    data() { 
     return { 
      loading: false, 
      randomProject: null, 
     } 
    }, 
    computed: { 
     projects() { 
      return this.$store.state.projects; 
     }, 
     commits() { 
      return this.$store.state.commits; 
     } 
    }, 
    methods : { 
     setCommit :()=> { 
      // code here 
     } 
    }, 
    watch: { 
     projects: (value) => { 
      this.setCommit() 
     } 
    }, 
    mounted() { 
     this.$store.dispatch('loadProjectsList') 
    } 
} 

我已經按照項目錯誤看回調:

this.setCommit is not a function 

我在回調把console.log (this),並顯示一個默認的對象不是VueComponent。

我做錯了什麼?

感謝您的幫助。

+1

這個不是100%,但試圖從'setCommit改變你的函數定義:()=> { }到'setCommit(){}'。也許項目方法也一樣。 –

+0

就是這樣。非常感謝你 !我是ES6的新手,我不知道其中的差別。 – amiceli

+1

沒問題,我也是新手。這就是我一直這樣做的方式。很高興我能幫上忙。 –

回答

4

而不是更改語法的嘗試和錯誤,並看看有什麼作品,如果你明白爲什麼一段特定的代碼有效,它會更好。

如VUE documentation提到:

不要實例屬性(例如vm.$watch('a', newVal => this.myMethod()))使用箭頭功能。由於箭頭函數綁定到父上下文,因此這個將不會是Vue實例,因爲您會期望它和this.myMethod將是未定義的。

如果您是es6的新功能箭頭功能here是一個相當不錯的箭頭函數的解釋這個綁定工程。

一旦你清楚再明白沒有更多的試驗和錯誤

希望我的回答是的你有所幫助

+0

回調是你*應該*使用箭頭函數的一個例子。 – Bert

+0

@BertEvans是你告訴我還是問miceli誰問這個問題。抱歉有點困惑? –

+0

你。您在回答中聲明:「不要在實例屬性或回調中使用箭頭函數」。實例屬性是正確的。回調不是。 – Bert