实现prop的双向绑定
一般在父子传参之间实现j简单的双向绑定要写这么一些代码:
// 主页面的内容
<template>
<div>
<buttn @click="show">点我显示子组件</button>
// 引入的子组件
<child :isShow="isShow" @closeShow="closeShow" v-show="!show"></child>
</div>
</template>
<script>
import child from '@/components/child';
export default {
components: {
child
},
data() {
return {
isShow: false, // 控制子组件的显隐
}
},
methods: {
show: {
this.isShow = true;
},
// 接收到的显隐值
closeShow(boolean) {
this.isShow = boolean;
}
}
}
</script>
// 子组件child的写法
<template>
<div>
<button @click="changeShow" v-show="show">点我隐藏自己</button>
<div>
</template>
<script>
export default {
props: ['isShow'],
data() {
return {
show: false, // 接收的显隐
}
},
watch: {
isShow: {
handler(newVal) {
if (newVal) this.show = newVal;
}
}
},
methods: {
changeShow() {
if (this.show) {
this.show = !this.show;
this.$emit('closeShow', this.show);
}
}
}
}
</script>
而使用.sync的区别在于
// 第一:修改 “引入子组件" 的地方
<child :isShow.sync="改变的值(要传递的值)"></child>
// 其实是方法isShow的缩写
@isShow ='(res) => isShow = res'
// 第二:修改this.$emit
props: ['isShow'];
this.$emit('update: isShow', this.show)
// update是固定的,isShow是我们要修改的状态值,与传入的状态名字相对应