abe*_*dev 7 javascript vue.js vuex vuejs2
我正在阅读有关Vue组件的文档,但是将Vuex数据用于组件属性。
从示例中可以看出,如果country_id在该data方法中运行良好。但是,当country_id计算属性从Vuex存储返回数据时,子组件的internalValue总是初始化为undefined。
我究竟做错了什么?
父组件:
export default {
computed: {
country_id() {
return this.$store.state.user.country_id
}
},
mounted: function () {
this.$store.dispatch('user/load');
}
}
Run Code Online (Sandbox Code Playgroud)
export default {
computed: {
country_id() {
return this.$store.state.user.country_id
}
},
mounted: function () {
this.$store.dispatch('user/load');
}
}
Run Code Online (Sandbox Code Playgroud)
子组件:
export default {
props: [ 'value' ],
data: function() {
return {
internalValue: null,
};
},
mounted: function() {
this.internalValue = this.value;
},
watch: {
'internalValue': function() {
this.$emit('input', this.internalValue);
}
}
};
Run Code Online (Sandbox Code Playgroud)
<template>
<child v-model="country_id"></child>
</template>
Run Code Online (Sandbox Code Playgroud)
在生命周期钩子触发之前,父组件将其所拥有的值传递country_id给其子组件。mounted因为你的$store.dispatch事情在那之前才发生,所以它最初是undefined。
您的子组件internalValue在其mounted生命周期钩子中设置其初始value属性为undefined。然后,当country_id父组件中的更新时,子组件的value属性将更新,但internalValue仍将保留undefined。
您internalValue还应该创建一个计算属性:
computed: {
internalValue() {
return this.value;
}
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以等待渲染子组件,直到country_id定义:
<child v-if="country_id !== undefined" v-model="country_id"></child>
Run Code Online (Sandbox Code Playgroud)