vue报错:
void 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:
这是由于子组件更新了父组件传入的属性值导致的,而vue不建议双向数据同步,要求数据是单向传递。然而,有时我们确实需要子组件与父组件更新同一个值,vue的解决方案如下:
子组件:
<template>
<div vi-if="visible">
我是子组件
<button @click="hide">关闭</button>
</div>
</template>
<script>
export default {
props: {
visible: {type: Boolean, default: false}
}
methods: {
hide () {
this.$emit('update:visible', false)
}
}
}
</script>
父组件:
<template>
<div>
<button @click="show">显示</button>
<child v-model="entity" :visible.sync="showChild"/>
</div>
</template>
<script>
export default {
components: {
'child': () => import('./child')
},
data () {
return {
showChild: false
}
},
methods: {
show() {
this.showEChild = true
}
}
}
</script>
关键点是父组件上面的 .sync 与子组件上面的 update: