2017-09-21 50 views
1

我有興趣製作一個自定義複選框組件,它將包含一些div和一些內容。Vuex:動態綁定到狀態的屬性

我有一個店,看起來像這樣:

var store = Vuex.Store({ 
    state: { 
    lights: true, 
    sound: false 
    } 
}); 

有沒有辦法,我可以創建一個可以接受這些屬性(lightssound)之一,並操縱他們的自定義組件什麼辦法?

我現在擁有一切真正的麻煩。我創建了一個模板:

<div id="app"> 
    <div class="container"> 
    <my-switch :name="'lights'"></my-switch> 
    <my-switch :name="'sound'"></my-switch> 
    </div> 
</div> 

接下來我用this as an example,並且試圖每個複選框綁定到店裏的一個屬性:

Vue.use(Vuex); 

var store = Vuex.Store({ 
    state: { 
    lights: true, 
    sound: false 
    }, 
    mutations: { 
    updateMessage(state, args) { 
     state[args.name] = args.value; 
    } 
    } 
}); 

Vue.component("my-switch", { 
    props: ["name"], 
    template: '<div>{{ name }} <input type="checkbox" v-model="checked"></div>', 
    computed: { 
    checked: { 
     get() { 
     return this.$store.state[this.name]; 
     }, 
     set(value) { 
     this.$store.commit("updateMessage", { name: this.name, value: value }); 
     } 
    } 
    } 
}); 

var v = new Vue({ 
    el: "#app", 
    store: store 
}); 

我已經演示這裏被打破: https://codepen.io/EightArmsHQ/pen/dVXeNL?editors=0010

問題是我收到以下錯誤:

TypeError: Cannot read property 'state' of undefined

回答

0

你需要通過new Vuex.Store({...})實例化Vuex店(我希望你的代碼拋出一個錯誤,但顯然不是。)

而且,你不需要Vue.use(Vuex)線。

Here's a working Codepen.

+0

哇哦,這就是尷尬...謝謝! – Djave