Vue.js 如何解决避免在vue中变异道具的问题
我的控制台中出现了这个错误 [Vue warn]:避免直接改变道具,因为每当父组件重新渲染时,该值将被覆盖。 相反,使用基于道具值的数据或计算属性。道具变异:“猫产品” 这是我的vue组件Vue.js 如何解决避免在vue中变异道具的问题,vue.js,Vue.js,我的控制台中出现了这个错误 [Vue warn]:避免直接改变道具,因为每当父组件重新渲染时,该值将被覆盖。 相反,使用基于道具值的数据或计算属性。道具变异:“猫产品” 这是我的vue组件 <template> <div> <table class="table table-striped"> <thead> <tr>
<template>
<div>
<table class="table table-striped">
<thead>
<tr>
<th>Product Name</th>
<th>Remove</th>
</tr>
</thead>
<tbody>
<tr v-for="product in catProducts">
<td>
{{ product.name }}
</td>
<td>
<button @click="remove(product)" class="btn btn-danger">Remove</button>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default{
props: ['category', 'catProducts'],
data(){
return {
}
},
methods: {
remove(product){
axios.delete('/category/products/'+this.category.id+'/'+product.id).then(response => {
this.catProducts = response.data.products;
});
}
}
}
</script>
品名
去除
{{product.name}
去除
导出默认值{
道具:['category','catProducts',],
数据(){
返回{
}
},
方法:{
移除(产品){
delete('/category/products/'+this.category.id+'/'+product.id)。然后(response=>{
this.catProducts=response.data.products;
});
}
}
}
什么response.data.products代码>退货是属于该类别的所有产品。
即使我的代码在删除该类别的产品方面做了它应该做的事情,
我的控制台中仍然存在避免突变道具的错误,我不确定如何修复它。这里有两个问题:
直接更改/变异道具catProducts
解决方案:向父组件发出类似“deleteProduct”的事件,以便它可以调用axios.delete
,然后获取刷新的产品列表并覆盖作为道具传递给子组件的产品列表
从HTTP DELETE方法返回新产品列表
解决方案:调用axios.delete
,如果成功,则调用axios.get
获取产品列表,并覆盖作为道具传递给子组件的产品列表
删除调用完成后
删除(产品){
delete('/category/products/'+this.category.id+'/'+product.id)。然后(response=>{
this.catProducts=response.data.products;
}
);
}
不是直接对道具进行变异,而是发出更新事件,以便可以在父组件中使用同步修改器来更新道具
删除(产品){
delete('/category/products/'+this.category.id+'/'+product.id)。然后(response=>{
这.$emit(“更新:catProducts”,response.data.products);
}
);
}
然后在父组件中,如果catProducts
是组件的状态
您从哪里获得的catProducts
?这是一个复制品,您需要做的就是将catProducts道具复制到一个数据变量中,然后您可以对其进行变异。此外,您不应该直接变异道具,但有一些方法可以解决此问题。将道具复制到数据可能是一种可能的修复方法,但我不认为它总是一种解决方案最佳实践。这完全取决于你从哪里得到道具