【问题标题】:Vue: initial triggering of a computed propertyVue:计算属性的初始触发
【发布时间】:2019-06-21 16:42:09
【问题描述】:

在我的 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.js vuejs2 vuex


    【解决方案1】:

    直到你使用它才会计算。

    console.log 它,或者直接写 currentOrganization;在代码中的某个地方执行,它会计算:)

    【讨论】:

    • 嗯,这很愚蠢。我的意思是,从 Vue 的角度来看。谢谢!
    • 为什么“最佳答案”被删除了? :'(
    • 因为事实证明问题更复杂。 typeof this.selectedOrganization 原来是“字符串”。在第一次运行时,currentOrganization() 返回null,因为没有任何内容符合过滤条件。在随后的运行中,它似乎将this.selectedOrganization 强制转换为整数,并返回结果。
    • 你会做小提琴吗?
    • b-form-select 发出的初始空值可能会破坏selectedOrganization。你可以试试普通的
    【解决方案2】:

    你应该确保你的计算总是返回一个值。 linter 会警告您该错误。很有可能你的条件失败了——也许this.selectedOrganization 是假的。

    【讨论】:

      猜你喜欢
      • 2018-12-29
      • 2017-07-22
      • 1970-01-01
      • 2020-02-03
      • 2018-01-25
      • 1970-01-01
      • 2020-12-01
      • 2021-05-04
      相关资源
      最近更新 更多