2016-11-11 48 views
4

小提琴:https://jsfiddle.net/mjvu6bn7/數據變量不被從觀察者更新在Vue.js計算屬性與Vuex

我有一個計算屬性,這對Vuex存儲的變量,它被異步設定的依賴性的觀察者。我試圖設置Vue組件的數據變量,當這個計算的屬性發生變化時,但是這沒有發生。

這裏是Vue的組件:

new Vue({ 
    el: '#app', 
    store, 
    data : { 
     myVar : "" 

    }, 
    beforeMount() { 
     this.$store.dispatch('FETCH_PETS', { 
     }).then(() => { 
        console.log("fetched pets") 
     }) 

    }, 
    computed:{ 
     pets(){ 
     return this.$store.state.pets 
     } 
    }, 
    watch:{ 
    pets: (pets) => { 
     console.log("Inside watcher") 
     this.myVar = "Hey" 
    } 
    } 
}); 

這裏是Vuex店:

const state = { 
    pets: [] 
}; 

const mutations = { 
    SET_PETS (state, response) { 
     console.log("SET_PETS") 
    state.pets = response; 
    } 
}; 

const actions = { 
FETCH_PETS: (state) => { 
     setTimeout(function() { 
      state.commit('SET_PETS', ['t7m12qbvb/apple_9', '6pat9znxz/1448127928_kiwi']) 
    }, 1000) 
} 
} 

const store = new Vuex.Store({ 
    state, 
    mutations, 
    actions 
}); 

Here是這創造小提琴。正如你所看到的,myVar沒有被更新,但是當寵物被加載時觀察者被調用。

回答

4

你錯過了一個事實,即ES6箭頭功能do not bind the this keyword(箭頭功能不是簡單的語法糖比普通function)。因此在您的示例中,this內部的pets觀察者默認爲windowmyVar,因此Vue實例從未設置。如果你改變你的代碼如下,它工作正常:

watch: { 
    pets(pets) { 
     console.log("Inside watcher") 
     this.myVar = "Hey" 
    } 
} 
1

這是因爲這不是你期望的內在功能。

試試這個:

watch:{ 
    var that = this; 
    pets: (pets) => { 
     console.log("Inside watcher") 
     that.myVar = "Hey" 
    } 
+1

這實際上是一個語法錯誤 - 你不能把變量聲明內的對象文字。 – Aletheios