首页 > 解决方案 > Vue:计算属性的初始触发

问题描述

在我的 Vue 组件中,我有一个计算属性,它监视状态和组件,并返回一个对象。

        currentOrganization () {
            if (this.$store.state.organizations && this.selectedOrganization) {
                return this.$store.state.organizations.filter(org => org.id === this.selectedOrganization)[0];
            }
        }

不幸的是,这个属性在组件加载时不会自动更新,尽管我可以看到我同时拥有this.$store.state.organizationsthis.selectedOrganization。但是,当我通过下面的选择组件向我的 Vuex 存储发送操作时,它会更新:

                <b-form-select id="orgSelect"
                               v-model="selectedOrganization"
                               :options="this.$store.state.organizations.map(org => {return {value: org.id, text:org.name}})"
                               size="sm"
                               v-on:input="currentOrganizationChange()"
                               class="w-75 mb-3">
                    <template slot="first">
                        <option :value="null" disabled>Change Organization</option>
                    </template>
                </b-form-select>

该组件调度一个 Vuex 动作:

            currentOrganizationChange () {
                this.$store.dispatch('setCurrentOrganization', this.selectedOrganization);
            },

我如何currentOrganization()最初进行计算?

标签: vue.jsvuejs2vuex

解决方案


在您使用它之前,计算不会计算。

console.log它,或者只是写当前的组织;在执行的代码中的某处,它将计算:)


推荐阅读