vue.js 为什么我的子组件要更新父组件?
vue.js Why is my child component updating the parent?
我有一个用作编辑部分的子组件。它在 created()
上复制一个道具作为编辑的 v 模型,因为我不希望在用户单击保存按钮之前对父级进行任何编辑。当用户单击保存时,我 $emit
将编辑后的模型返回给父级进行更新。理论上。
实际上,每当我编辑子组件时,父模型似乎都是反应式的,尽管子组件 <input>
应该作用于传递的 prop 的副本。为什么会这样,我该如何预防?
<h2>{{ location.name }}</h2>
<edit-location v-if="editing" :location="location" />
EditLocation.vue:
<template>
<input v-model="copyOfLocation.name">
<button>Save</button>
</template>
<script>
export default {
props: {
location: {
required: false,
type: Object,
},
},
data() {
return {
copyOfLocation: {},
}
},
created() {
this.copyOfLocation = this.location;
},
}
</script>
虽然把location
的值赋给了copyOfLocation
,实际上是赋值了引用。这使问题。
尝试
this.copyOfLocation = JSON.stringify(JSON.parse(this.location));
同时复制 created
挂钩中的值。这不会复制引用。
this.copyOfLocation = _.cloneDeep(this.location); // cloning using Lodash library.
我有一个用作编辑部分的子组件。它在 created()
上复制一个道具作为编辑的 v 模型,因为我不希望在用户单击保存按钮之前对父级进行任何编辑。当用户单击保存时,我 $emit
将编辑后的模型返回给父级进行更新。理论上。
实际上,每当我编辑子组件时,父模型似乎都是反应式的,尽管子组件 <input>
应该作用于传递的 prop 的副本。为什么会这样,我该如何预防?
<h2>{{ location.name }}</h2>
<edit-location v-if="editing" :location="location" />
EditLocation.vue:
<template>
<input v-model="copyOfLocation.name">
<button>Save</button>
</template>
<script>
export default {
props: {
location: {
required: false,
type: Object,
},
},
data() {
return {
copyOfLocation: {},
}
},
created() {
this.copyOfLocation = this.location;
},
}
</script>
虽然把location
的值赋给了copyOfLocation
,实际上是赋值了引用。这使问题。
尝试
this.copyOfLocation = JSON.stringify(JSON.parse(this.location));
同时复制 created
挂钩中的值。这不会复制引用。
this.copyOfLocation = _.cloneDeep(this.location); // cloning using Lodash library.