2016-09-14 63 views
1

下面的簡單代碼給了我很多頭痛,因爲some-component和root實例都向控制檯記錄錯誤,而不是從vuex對象進行綁定。我可能會在這裏錯過什麼?Vuex不能在子組件中工作

var state = { 
 
\t counter: 0 
 
}; 
 
var mutations = {}; 
 
var store = new Vuex.Store({state, mutations}); 
 

 
var someComponent = Vue.extend({ 
 
    template: '<div>{{counter}}</div>', 
 
    //data: function(){return {counter: 0}}, 
 
    vuex: { 
 
    getters: { 
 
     counter: getCounter 
 
    } 
 
    } 
 
}); 
 

 
new Vue({ 
 
    el: '#app', 
 
    components: { 
 
    \t 'some-component': someComponent 
 
    }, 
 
    store: store, 
 
    vuex: { 
 
    \t getters: { 
 
    \t \t counter: getCounter 
 
    \t } 
 
    } 
 
}); 
 

 

 
function getCounter(state) { 
 
    return state.counter; 
 
}
<!DOCTYPE html> 
 
<html lang="en"> 
 
    <head> 
 
    <meta charset="utf-8"> 
 
    <title>vue-bug</title> 
 
    </head> 
 
    <body> 
 
    <div id="app"> 
 
    \t <span>{{counter}}</span> 
 
    \t <some-component></some-component> 
 
    </div> 
 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.0-rc.1/vue.js"></script> 
 
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vuex/2.0.0-rc.1/vuex.js"></script> 
 
    </body> 
 
</html>

在我的代碼,我打電話Vue.use(Vuex),但在這種撥弄我沒有(它說,Vuex已註冊)。此外,請注意,如果您取消註釋該行的數據,該組件呈現正確。

任何幫助,非常感謝。

+0

如果您使用'Vue 2.0',您應該使用'Vuex 2.0'。我不能100%確定Vue.js 2.0與您使用的Vuex版本兼容。你能升級到Vuex 2.0嗎? 你可以在你的組件中添加'created'鉤子並執行'console.log(this。$ store)'來查看你的商店是否被注入到你的組件中? 提供jsFiddle,它更容易調試,然後查看上面的代碼。 –

+0

@PrimozRome我大量編輯了我的原始問題,以便重現和更新vuex版本。此外,'console.log(this。$ store)'告訴我商店正在被注入。謝謝! – Ozymas

回答

3

如果你使用的是Vue/Vuex 2.0,你應該看看link。在vuex 2.0中,您不會在組件內創建屬性vuex來設置您的獲取者和操作。相反,在你store.js文件定義了一個干將對象,其中你會得到從國家的道具,然後將其注入到店裏,像這樣:

const state = { 
    counter: 0 
} 
const getters = { 
    getCounter: state.counter 
} 

const actions = {} 
const mutations = {} 

export default new Vuex.Store({ 
    state, 
    getters, 
    actions, 
    mutations, 
}) 

在你的組件,你可以使用如下公式計算性能只是定義一個getter ,像這樣:

import { mapGetter, mapActions } from 'vuex' 

export default { 
    template: '#some-template', 
    computed: { 
     yourFirstComputed() {}, 
     anotherOfYourComputed() {}, 
     ...mapGetters({ 
      getCounter: 'getCounter' 
     }) 
    }, 
    methods: { 
     yourMethod(){}, 
     ...mapActions({ 
      anyOfYourActions: 'anyOfYourActions' 
     }) 
    } 
} 

然後你可以像使用普通計算一樣調用這些道具。 我重申,這適用於vuex 2,我認爲你在閱讀問題的評論後使用了vuex 2。

我希望它有幫助!

+0

謝謝,這似乎解決了它!根據發行說明,vuex組件選項已被棄用。我所要做的就是在將getter和action傳遞給商店構造函數並且組件現在正常工作之後,添加'calculate:Vuex.mapGetters(['counter'])''。 – Ozymas

+0

很高興我可以幫忙;) –

+0

只是一個快速更新,任何人都可能會發現這個相同的問題:即使答案是正確的,我需要再做一步,以通過需求工作獲得我的組件。正如[本期](https://github.com/vuejs/vuex/issues/264)中所討論的那樣,你需要用'vue'從'vue/dist/vue'替換'import Vue' '。另外,您需要爲您的webpack config解析對象添加一個別名:別名:vue:vue/dist/vue.js:' }'。 – Ozymas