vue中的sync 以及 sync 控制子组件的显示与隐藏

本文介绍了Vue中使用.sync修饰符实现父子组件间优雅的双向绑定。通过示例展示了如何从父组件传递参数到子组件,并通过子组件的自定义事件更新父组件的状态,从而实现子组件关闭时通知父组件更新显示。同时,提供了完整的代码实现,包括父组件显示和关闭子组件的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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,子组件页面显示。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值