【Vue2.x】.sync

1. Introduction

官方文档:vue .sync 修饰符

  • .sync 修饰符以前存在于vue1.0版本里,但是在在 2.0 中移除了 .sync 。但是在 2.0 发布之后的实际应用中,我们发现 .sync 还是有其适用之处,比如在开发可复用的组件库时。我们需要做的只是让子组件改变父组件状态的代码更容易被区分。
  • 从 2.3.0 起我们重新引入了 .sync 修饰符,但是这次它只是作为一个编译时的语法糖存在。它会被扩展为一个自动更新父组件属性的 v-on 监听器。

2. Code

2.1 Basic Function

<comp :foo.sync="bar"></comp>

被扩展为:

<comp :foo="bar" @update:foo="val => bar = val"></comp>

当子组件需要更新 foo 的值时,它需要显式地触发一个更新事件:

this.$emit('update:foo', newValue)
<template>
    <div class="details">
        <myComponent :show.sync='valueChild' style="padding: 30px 20px 30px 5px;border:1px solid #ddd;margin-bottom: 10px;"></myComponent>
        <button @click="changeValue">toggle</button>
    </div>
</template>
<script>
import Vue from 'vue'
Vue.component('myComponent', {
      template: `<div v-if="show">
                    <p>默认初始值是{{show}},所以是显示的</p>
                    <button @click.stop="closeDiv">关闭</button>
                 </div>`,
      props:['show'],
      methods: {
        closeDiv() {
          this.$emit('update:show', false); //触发 input 事件,并传入新值
        }
      }
})
export default{
    data(){
        return{
            valueChild:true,
        }
    },
    methods:{
        changeValue(){
            this.valueChild = !this.valueChild
        }
    }
}
</script>

2.2 v-bind

<template>
 <div>
   <h1>父组件:{{doc.title}}--{{doc.content}}</h1>
   <Child v-bind.sync="doc"></Child>
 </div>
</template>
 
<script>
import Child from './child.vue'
export default {
  data() { 
    return {
      doc:{
         title:'前端',
         content:'Vue',
      },
    } 
  }, 
  components:{
    Child
  },
}
</script> 
javascript
复制代码
<template>
  <div class="child">
    <h4>{{title}}--{{content}}</h4>
    <button @click="change">改变</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      newTitle:'明天也要努力'
    };
  },
  props: {
    title:{
      type:String,
      default:'',    
    },
    content:{
      type:String,
      default:'',    
    }
  },
  methods:{
    change(){
      this.$emit('update:title',this.newTitle);
      this.$emit('update:content','Vue中 子组件向父组件传值 及 .sync 修饰符 详解');
    },
  },
};
</script>