vue .sync的理解

457 阅读1分钟

.sync其实还是一个语法糖,用于子组件修改父组件的数据,vue是单向数据流,但是使用了.sync从而可以实现双向数据流.

底层还是用的父组件通过props传递给子组件,并且父组件绑定一个自定义事件,自定义事件分发是一个回调函数,所以能实现这个效果

例子

//父组件
<template>
  <div id="app">
    <button @click="change">是否展示子组件</button>
    //非简写版
    <Child 
        v-show="isTrue" 
        :isShow="isTrue" 
        @update:isShow="val => isTrue = val"/>
    //简写版
    <!-- <Child v-show="isTrue" :isShow.sync="isTrue"/> -->
  </div>
</template>

<script>
import Child from '@/components/Child.vue';
export default {
  name: 'App',
  data(){
    return {
      isTrue:true
    }
  },
  methods:{
    change(){
      this.isTrue = !this.isTrue;
    }
  },
  components: {
    Child
  }
}
</script>
//子组件
<template>
  <div style="background:gray;height:200px;line-height:200px" v-if="isShow">
    <h3>我是子组件的内容</h3>
    <button @click="edit">我是子组件的按钮</button>
  </div>
</template>
<script>
  export default {
    name:'-Child',
    props: ['isShow'],
    methods: {
      edit() {
        this.$emit('update:isShow', false);
      }
    }
  }
</script>