【问题标题】:Vuex + VueJS: Passing computed property to child is undefinedVuex + VueJS:未定义将计算属性传递给孩子
【发布时间】:2017-10-17 21:56:24
【问题描述】:

我正在阅读这个documentation on Vue components,但我的组件属性使用了 Vuex 数据。

从示例中,如果country_iddata 方法中,它可以正常工作。但是当country_id 是从Vuex 存储返回数据的计算属性时,子组件的internalValue 总是初始化为undefined

我做错了什么?

父组件:

export default {
    computed: {
        country_id() {
            return this.$store.state.user.country_id
        }
    },
    mounted: function () {
        this.$store.dispatch('user/load');
    }
}
<template>
   <child v-model="country_id"></child>
</template>

子组件:

export default {
    props: [ 'value' ],
    data: function() {
        return {
            internalValue: null,
        };
    },
    mounted: function() {
        this.internalValue = this.value;
    },
    watch: {
        'internalValue': function() {
            this.$emit('input', this.internalValue);
        }
    }
};
<template>
   <p>Value:{{value}}</p>
   <p>InternalValue:{{internalValue}}</p>
</template>

【问题讨论】:

    标签: javascript vue.js vuejs2 vuex


    【解决方案1】:

    在触发mounted 生命周期钩子之前,您的父组件将其对country_id 的值传递给其子组件。由于您的 $store.dispatch 直到那时才发生,它最初是 undefined

    您的子组件在其 mounted 生命周期钩子中使用 undefined 的初始 value 属性设置其 internalValue。然后,当父组件中的country_id 更新时,您的子组件的value 属性将更新,但internalValue 将保持undefined

    您也应该将internalValue 设为计算属性:

    computed: {
      internalValue() {
        return this.value;
      }
    }
    

    或者,您可以等到定义 country_id 后再渲染子组件:

    <child v-if="country_id !== undefined" v-model="country_id"></child>
    

    【讨论】:

      猜你喜欢
      • 2018-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-12
      • 2021-01-05
      • 2019-07-14
      • 1970-01-01
      • 2021-10-16
      相关资源
      最近更新 更多