【问题标题】:Vue Value computed from props is undefined when prop is dynamically set with Vuex getter当使用 Vuex getter 动态设置 prop 时,从 props 计算的 Vue 值未定义
【发布时间】:2019-11-17 22:49:50
【问题描述】:

我已经为类似 mattrialdesign 的开关构建了一个小组件。可以使用“活动”属性设置开关的状态。为了切换状态,我使用计算值,因为无法更改道具。

如果我将组件标签与硬编码的“活动”道具一起使用,它就可以工作。 如果我使用 vuex getter 来设置 prop,则 prop get 是正确的值,但计算结果是“未定义”。

这里是组件:

<template>
    <div class="flex items-center">
        <div class="flex h-6 rounded-full shadow w-12 cursor-pointer" :class="status" @click="toggle">
            <div class="flex h-6 rounded-full shadow w-6 bg-blue-500">
                <slot></slot>
            </div>
        </div>
        <label class="m-0 ml-2 text-lg normal-case">{{label}}</label>
    </div>
</template>
<script>
    export default{
        props:{
            active: Boolean,
            label: String
        },
        data() {
            return { isActive: this.active }
        },
        computed:{
            status(){

                return this.isActive ? 'justify-end bg-success' : 'justify-start bg-primary';
            }
        },
        methods:{
            toggle(){
                this.isActive = !this.isActive;
            },
        }
    }
</script>

这行得通:

<toggle label="Foo" active="true">Foo</toggle>

这不是:

<toggle label="Foo" :active="this.$store.getters.FooStatus">Foo</toggle>

在 Vue Devtools 中,我可以看到 active 是 true/false,具体取决于 FooStatus,但 isActive 是未定义的。

【问题讨论】:

    标签: vuejs2 vue-component vuex


    【解决方案1】:

    我注意到两件事:

    • 在第一个用例中,您将active 属性设置为字符串值true。您应该使用 :active="true" 或更好,但仅使用 active 而不带参数。
    • 在第二个用例中,您不应该使用this,因为模板已经使用本地范围内的所有属性、方法等进行了评估。 IE。它应该只是
    :active="$store.getters.FooStatus"
    

    更改未传播的原因可能是因为该属性不是反应性的。例如,如果从 vuex 传递给:active 的初始值是undefined,就会发生这种情况。所以你应该定义一个默认值:

    active: {
      default: false,
      type: Boolean
    }
    

    或者,您可以为数据字段分配适当的值:

    data() {
      return {
        isActive: Boolean(this.active)
      };
    }
    

    【讨论】:

      【解决方案2】:

      我按照您的建议更改了代码,现在无论 active 属性是 true 还是 false,isActive 都是 false。你是对的,看起来 Vuex 的初始值是未定义的。并且由于某种原因 isActive 不会在活动更改时更新。所以我的“quick&dirty”解决方案是在活动时添加一个手表:

       watch: {
          active: function active() {
            this.isActive = Boolean(this.active);
          }
        }
      

      【讨论】:

        猜你喜欢
        • 2021-02-15
        • 1970-01-01
        • 2020-07-30
        • 2018-04-04
        • 2020-10-05
        • 2020-01-30
        • 1970-01-01
        • 2019-07-31
        • 2019-10-19
        相关资源
        最近更新 更多