我有一个 vuex 商店。在 vuex 商店中更改状态偏好。我想重新渲染 DOM。我希望每次 vuex 存储中的状态偏好更改时调用 checkValue 方法。
索引.html
<div id="app">
<my-component></my-component>
<my-other-component></my-other-component>
</div>
vue 已经初始化,这里也导入了 store
我的组件.js
Vue.component('my-component',require('./MyComponent.vue'));
import store from "./store.js"
Vue.component('my-other-component',require('./MyOtherComponent.vue'));
import store from "./store.js"
new Vue({
el : "#app",
data : {},
store,
method : {},
})
DOM 需要根据商店中的状态偏好更改而更改的组件
我的组件.vue
<template>
<div v-for="object in objects" v-if="checkValue(object)">
<p>hello</p>
</div>
</template>
<script>
methods : {
checkValue : function(object) {
if(this.preference) {
// perform some logic on preference
// logic results true or false
// return the result
}
}
},
computed : {
preference : function() {
return this.$store.getters.getPreference;
}
}
</script>
Vuex 存储文件
商店.js
const store = new Vuex.Store({
state : {
preferenceList : {components : {}},
},
getters : {
getPreference : state => {
return state.preferenceList;
}
},
mutations : {
setPreference : (state, payload) {
state.preference['component'] = {object_id : payload.object_id}
}
}
点击 li 元素更新 vuex 存储的组件。
我的其他组件.vue
<div>
<li v-for="component in components" @click="componentClicked(object)">
</li>
</div>
<script type="text/javascript">
methods : {
componentClicked : function(object) {
let payload = {};
payload.object_id = object.id;
this.$store.commit('setPreference', payload);
}
}
</script>
原文由 Tomonso Ejang 发布,翻译遵循 CC BY-SA 4.0 许可协议
方法不是反应性 的,
所以这意味着你需要使用一个 computed 来计算你需要的东西,但是 computed 不接受参数而你需要对象,所以解决方案是创建另一个接受对象作为属性的组件,然后在那里执行逻辑:
我的其他组件.vue:
然后在原始组件中: