v-如果未在计算属性上触发

Tom*_*ang 7 vue.js vuex

我有一个vuex商店.在vuex商店中改变国家偏好.我想重新渲染DOM.我希望每次vuex商店中的状态首选项发生变化时都会调用checkValue方法.

的index.html

<div id="app">
    <my-component></my-component>
    <my-other-component></my-other-component>
</div>
Run Code Online (Sandbox Code Playgroud)

vue已初始化,并且此处也导入了商店

my_component.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 : {},
})
Run Code Online (Sandbox Code Playgroud)

在存储中更改状态首选项时需要更改DOM的组件

MyComponent.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>
Run Code Online (Sandbox Code Playgroud)

Vuex商店文件

store.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}
    }
}
Run Code Online (Sandbox Code Playgroud)

单击li元素时更新vuex存储的组件.

MyOtherComponent.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>
Run Code Online (Sandbox Code Playgroud)

Tom*_*mer 7

方法不是响应式的,这意味着它们不会跟踪更改并在发生更改时重新运行。这就是你计算出来的。

所以这意味着你需要使用一个计算来计算你需要的东西,但计算不接受参数并且你需要对象,所以解决方案是创建一个接受对象作为属性的另一个组件,然后在那里执行逻辑:

MyOtherComponent.vue:

<template>
    <div v-if="checkValue">
        <p>hello</p>
    </div>
</template>


<script>
    props:['object','preference']
    computed : {
        checkValue : function() {
             if(this.preference) {
               // perform some logic on preference
               // logic results true or false
               return true
             }

             return false
        }
    }


</script>
Run Code Online (Sandbox Code Playgroud)

然后在原始组件中:

<template>
    <my-other-component v-for="object in objects" :object="object" :preference="preference">
        <p>hello</p>
    </my-other-component>
</template>
Run Code Online (Sandbox Code Playgroud)