gpt4 book ai didi

javascript - 避免直接修改 prop,因为只要父组件重新渲染,该值就会被覆盖

转载 作者:搜寻专家 更新时间:2023-10-30 22:31:04 26 4
gpt4 key购买 nike

我是 vuejs 的新手,我正在尝试将 active 数据同步到父级但出现错误

vue.js:523 [Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "active" (found in component )

我的Vuejs代码如下

<div id="app">
<pre>
{{$data}}
</pre>
<div v-for="plan in plans">
<plan :plan="plan" :active.sync="active"></plan>
</div>
</div>
<template id="mytemplate">
<div>
{{$data}}
<span>{{plan.name}}</span>
<span>{{plan.price}}</span>
<button @click="setActivePlan">upgrade</button>
</div>
</template>

<script src="vue.js"></script>
<script>
new Vue({
el: "#app",

data: {
active:this.active,
plans: [
{name: 'Diamond', price: '1000'},
{name: 'Gold', price: '500'},
{name: 'Silver', price: '250'},
{name: 'Free', price: '0'}
]
},
components: {
plan: {
template: "#mytemplate",
props: ['plan', 'active'],
methods: {
setActivePlan: function () {
this.active = this.plan
}
}
}
}

});
</script>

谁能帮我解决这个问题

最佳答案

正如错误提示的那样,您正在尝试更改 Prop 之一 active

Prop being mutated: "active" (found in component )

由于 props 是从父级动态发送的,因此只要父级更改它们,它们就会更改,如果您在子级中也更改它们,则会发生冲突,这就是您收到此错误的原因。

作为 documentation :

the parent-child component relationship can be summarized as props down, events up. The parent passes data down to the child via props, and the child sends messages to the parent via events.

所以正确的做法是emit一个事件,它将调用父级中的方法并更改定义它的父级中的变量 active。以下是代码更改:

<script src="vue.js"></script>
<script>
new Vue({
el: "#app",

data: {
active:this.active,
plans: [
{name: 'Diamond', price: '1000'},
{name: 'Gold', price: '500'},
{name: 'Silver', price: '250'},
{name: 'Free', price: '0'}
]
},
methods: {
setActivePlan: function (plan) {
this.active = plan
}
}
components: {
plan: {
template: "#mytemplate",
props: ['plan', 'active'],
methods: {
setActivePlan: function () {
this.$emit('setActivePlan', this.plan)
}
}
}
}

});
</script>

关于javascript - 避免直接修改 prop,因为只要父组件重新渲染,该值就会被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41215773/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com