代码之家  ›  专栏  ›  技术社区  ›  Boris K

Vue:计算属性的初始触发

  •  1
  • Boris K  · 技术社区  · 7 年前

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

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

    不幸的是,当组件加载时,这个属性不会自动更新,尽管我可以看到我同时拥有这两个属性 this.$store.state.organizations this.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() 最初计算?

    2 回复  |  直到 7 年前
        1
  •  4
  •   Kick Buttowski    4 年前

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

    console.log 或者只写当前组织;在代码的某个地方执行并计算:)

        2
  •  0
  •   Tristan Shelton    7 年前

    你应该确保你的计算总是返回一个值。一个林特会警告你这个错误的。很可能你的病情正在恶化——也许吧 this.selectedOrganization 是法尔西。