我已经为这个问题苦苦挣扎了几个小时: 我在父组件中动态实例化了一个子 vue 组件,并传入了 propsData 一些父组件的数据。当父级更新时,动态创建的子级属性似乎不会更新。
请检查example我创建是为了更好地理解(从 chinchang 的示例中 fork 出来)
如您所见,我正在动态和静态实例化 Button 组件。按钮的颜色取决于类型属性。我将父级的数据(类型属性)作为 Prop 传递给动态和静态创建的实例。当您插入新按钮时,通过单击“单击插入”按钮,将使用父级的当前类型创建一个新按钮。单击事件之后,我切换父级的类型属性。正如您所看到的,静态创建的按钮实例(位于页面顶部)改变了颜色,但动态实例化的按钮实例保持不变。
您能指出我的错误并帮助找到解决方案吗?
谢谢, 阿贝尔
最佳答案
来自the docs :
Pass props to an instance during its creation. This is primarily intended to make unit testing easier.
设置 propsData
不会创建父子关系。它只是向组件提供(非 react 性)数据。简而言之,您选择了一种不太 Vue 的方法。您不应该关心创建组件,您的 View 模型中应该有数据项,然后 Vue 会为其创建组件。
export default {
name: 'app',
components: { Button },
data(){
return {
type: 'secondary',
buttons: []
};
},
methods: {
onClick() {
this.buttons.push(true);
if(this.type === 'primary'){
this.type = 'secondary';
} else {
this.type = 'primary';
}
}
}
}
和
<div ref="container">
<button @click="onClick">Click to insert</button>
<Button v-for="b in buttons" :type="type">Click me!</Button>
</div>
关于javascript - Vue propsData 不动态更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48662160/