vue中的.sync
官方推荐使用一种update:my-prop-name 的模式来替代事件触发,目的是为了优雅而不粗鲁的实现父子组件间的双向绑定!先来完成一个小功能:
在父组件,定义show:false;
点击按钮,使得show=true,弹出子组件;
子组件中,点击按钮,使得show=false,这个show的值传回给父组件;
涉及到父组件给子组件传参,子组件自定义事件传回给父组件;
父组件
<template>
<div>
<h3>父组件布局</h3>
<p v-if="show">你能看见我吗?</p>
<p>-------</p>
<!-- :show = show 接收prop出来的值;@update是自定义事件 ,$event是子传给父的val,默认-->
<!-- <children :show = 'show' @update='show = $event'></children> -->
<!-- <children :show = 'show' @update:show='show = $event'></children> -->
<children :show.sync="show"></children>
</div>
</template>
<script>
import Children from "./Children";
export default {
components: {
Children
},
data() {
return {
show: false
};
},
methods: {
// update(val){
// console.log(val)
// this.show = val;
// }
}
};
</script>
子组件
<template>
<div>
<h3>我是子组件</h3>
<button @click="handle">点我</button>
</div>
</template>
<script>
export default {
data() {
return {};
},
props: ["show"], //父组件传过来的值,不可以直接修改;
methods: {
handle() {
console.log(1111);
// this.$emit('update', !this.show)
this.$emit("update:show", !this.show); //添加:show,修改的是show,就加show
}
}
};
</script>
应用: 父组件点击按钮,弹出子组件,子组件点击右上角关闭按钮,页面关闭;
父组件:
<template>
<div>
<h3>父组件布局</h3>
<button @click="showChildren">显示弹框</button>
<children :show.sync="show"></children>
</div>
</template>
<script>
import Children from "./Children";
export default {
components: {
Children
},
data() {
return {
show: false
};
},
methods: {
// 点击按钮,打开子组件
showChildren(){
this.show = true;
}
}
};
</script>
子组件:
<template>
<div v-show="show">
<h3>我是子组件</h3>
<button @click="handle">点我关闭子组件</button>
</div>
</template>
<script>
export default {
data() {
return {};
},
props: {
show: { //接收父组件传过来的值,不可以直接修改;
type: Boolean,
}
},
methods: {
// 关闭子组件,同时把关闭事件传给父组件
handle() {
console.log(1111);
// this.$emit('update', !this.show)
this.$emit("update:show", !this.show); //添加:show,修改的是show,就加show
}
}
};
</script>
注释: 子组件通过添加v-show=“show”, show的值从父组件传过来的,刚开始是默认是false,父组件点击按钮后,show的值从false变为true,子组件页面显示。