【发布时间】:2020-05-16 11:06:08
【问题描述】:
我正在开发一个 VueJS 项目,并且有这样的父/子组件。
Parent.vue
<template>
<ChildA v-bind="this.postData.someDataA" />
...
<ChildZ v-bind="this.postData.someDataZ"/>
<button @click="save">Save</button>
</template>
<script>
import ChildA from './ChildA';
...
import ChildZ from '.ChildZ';
data() {
return {
postData: {
someDataA: {field1: 'initialValue'}
someDataB: { // no initial value'}
...
},
},
methods: {
save() {this.$root.db.save(this.postData)}
}
</script>
Child.vue
<template>
<input type="text" v-model="field1" />
...
<input type="text" v-model="field10" />
</template>
<script>
props: {
field1:{type: String, default: 'default if not set by parent'},
...
}
</script>
如您所见,我想将 this.postData 从 Parent.vue 传递给将其保存到数据库的函数。但是,someDataA 等的值来自Child.vue。
当我像这样运行我的代码时,我收到了 Vue 警告:
Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders.
现在,我的问题是,处理这种情况的最佳做法是什么?我是否必须为每个子元素实现<ChildA @change="setSomeDataA()" />,并且每次子道具的值发生变化时$emit 一个事件?
【问题讨论】:
-
有时我更喜欢使用
this.$parent从孩子那里访问父数据 -
但是你不应该在子组件中使用 props 作为 v-model 值
-
请查看answer
-
@ChristianCarrillo 我应该怎么做呢?如果我想在
Child.vue中修改someDataA?
标签: vue.js