出现Avoid mutating a prop directly since the value will错误 已解决
出现这种情况的原因是我们直接改变子组件的props值,众所周知,props是父向子传值的一种形式。当我们子组件的props值要改变的时候,不能直接通过改变子组件的props来改变父组件。例如:父组件<template><div id="app"><son v-model="count" /></div></template><scr
·
出现这种情况的原因是我们直接改变子组件的props值,众所周知,props是父向子传值的一种形式。当我们子组件的props值要改变的时候,不能直接通过改变子组件的props来改变父组件。
例如:
父组件
<template>
<div id="app">
<son v-model="count" />
</div>
</template>
<script>
import son from "./components/son"
export default {
name: "App",
components: {
son
},
data() {
return {
count:150
};
},
};
</script>
子组件:
<template>
<div>
<input type="text" v-model.number="value">
<button @click="handleClick">按钮</button>
</div>
</template>
<script>
export default {
name:"son",
props: {
value:{
type:Number
}
},
methods:{
handleClick(){
this.$emit('input',100)
}
}
}
</script>
<style>
</style>
当我们直接在输入框里边修改时,会触发input的v-model,也就是会反向改变props,会出先一下错误: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: "value"found in…
解决方式
- 使用computed方式
<template>
<div>
<input type="text" v-model.number="count" />
<button @click="handleClick">按钮</button>
</div>
</template>
<script>
export default {
name: "son",
props: {
value: {
type: Number,
},
},
computed: {
count: {
get() {
return this.value;
},
set(newValue) {
this.$emit("input", newValue);
},
},
},
methods: {
handleClick() {
this.$emit("input", 100);
},
},
};
</script>
- data加watch
<template>
<div>
<input type="text" v-model.number="count" />
<button @click="handleClick">按钮</button>
</div>
</template>
<script>
export default {
name: "son",
watch:{
count:{
handler(newValue){
this.$emit('input',newValue)
}
}
},
props: {
value: {
type: Number,
},
},
data(){
return {
count:this.value
}
},
methods:{
handleClick(){
this.$emit('input',100)
}
}
};
</script>
<style></style>
更多推荐
已为社区贡献3条内容
所有评论(0)