2017-10-17 87 views
0

我目前做如下:2种方式与对象内嵌套的属性绑定。 (VueJS + VueX)

<script> 
export default { 
    computed: { 
    editingItem: { 
     get() { 
     return this.$store.getters['editing/editingItem']; 
     }, 
     set(newValue) { 
     this.$store.commit('editing/UPDATE_EDITING', newValue); 
     } 
    }, 
    editingItemName: { 
     get() { 
     return this.editingItem.name; 
     }, 
     set(newValue) { 
     this.editingItem.name = newValue; 
     this.editingItem = this.editingItem; 
     } 
    } 
    }, 
} 
</script> 

我是不是在复杂呢? editingItemName set()的第二行是解决方法,使editItem set()函数触发。

+0

你能解释一下你正在试图acheive什么?你是否试图实现与商店的双向数据绑定? – LiranC

+0

@LiranC是的。我可以用一个简单的状态值来做到这一点,但是如果它有嵌套的参数,我不得不像我做过的那样做,或者为Store上的每个参数提交一个提交。我喜欢这个例子的原因是,这样我只需要有一个突变。 –

回答

1

Check this article。它是关于表单的,但是它展示了用vuex实现双向绑定的方法。

关于您的特殊情况,请参阅代码。 telephone是对象内部的嵌套属性。

myModule.js

const myModule = { 
    state: { 
    customerInfo: { 
     name: '', 
     telephone: '' 
    } 
    }, 
    getters: { 
    getTelephone(state) { 
     return state.customerInfo.telephone 
    } 
    }, 
    mutations: { 
    setTelephone(state, payload) { 
     state.customerInfo.telephone += payload 
    }, 
    } 
} 
export default myModule; 

form.vue

<template> 
    <div> 
    <input v-model="telephone"></input> 
    </div> 
</template> 

<script> 
export default { 
    computed: { 
    telephone: { 
     get() { 
     return this.$store.getters['getTelephone'] 
     }, 
     set(value) { 
     this.$store.commit('setTelephone', value) 
     } 
    }, 
    } 
} 
</script> 
+0

很酷。它看起来像我正在做的 - 除此之外,我对每个嵌套参数重复使用相同的突变。你认为我应该对每个参数进行一次突变,或者我正在做的是好的吗?将您的答案标记为正确,因为我认为这是现在的方式! –