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: “show”
这个错误的意思是在子组件直接修改了父组件传递过来的参数,打破了vue父子传值单向流的规则。
具体的做法是在子组件通过this.$emit定义方法,在父组件接受方法,来改变传递过来的参数。
//父组件代码
<script>
//子组件的位置
import Test from './test.vue'
export default {
name: 'home',
data() {
return {
show: false
}
},
}
</script>
<template>
<div>
<Test :show="show"></Test>
</div>
</template>
<style scoped lang="less">
</style>
//子组件代码
<script>
export default {
name: 'test',
props: {
show: {
type: Boolean,
default: false
}
},
data() {
return {
}
},
mounted() {
},
methods: {
//重要!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//这样一样可以关闭子组件,但是就会报刚才的错误
// onclose(){
// this.show = false
// },
//正确的做法
// 子组件做下面的操作
onclose(){
this.$emit('onClose')
}
}
</script>
<template>
<div>
<div v-if="show">
<div >我是子组件</div>
<button @click="onclose">子组件关闭</button>
</div>
</div>
</template>
<style scoped lang="less">
</style>
//修改后的父组件
<script>
//子组件的位置
import Test from './test.vue'
export default {
name: 'home',
data() {
return {
show: false
}
},
methods: {
onClose(){
this.show = false
},
}
}
</script>
<template>
<div>
<Test :show="show" @onClose='onClose'></Test>
</div>
</template>
<style scoped lang="less">
</style>