vue 的sync用法

这个关键字在v2.3.0+ 新增,注意带有 .sync 修饰符的 v-bind 不能和表达式一起使用 (例如 v-bind:title.sync=”doc.title + ‘!’” 是无效的)。说白了他就是子组件改变父组件DATA的一种方法,但是个人觉得要慎用吧,不然有容易污染组件数据的隐患,

可以运行一下示例代码,参考vue  dev  tool ,就会明白

father.vue:

<template>
  <div class="hello">

    //input实时改变wrd的值, 并且会实时改变box里的内容
    <input type="text" v-model="wrd">
    <hr>
    这是name---{{sname}}
    <!-- 不写sync不更新父组件数据,变成了单向的父组件传值给子组件的写法 -->
    <box :word.sync="wrd" :sname.sync="sname" ></box>
  </div>
</template>

<script>
import box from './child.vue'  //引入box子组件
export default {
  name: 'HelloWorld',
  data() {
    return {
      wrd: '',
      sname:'zs',
      age:12
    }
  },
  components: {
    box
  }  
}
</script>

child.vue

<template>
  <div class="hello">
    <div class="ipt">
      <hr>
      ---------------------------------------------
      <br>
      <input type="text" v-model="str">
    </div>

    //word是父元素传过来的
    <br>
    <h2>{{ word }}</h2>
    <br>
    //sname也是
    <br>
  <h2>{{ sname }}</h2>
  </div>
</template>

<script>
export default {
  name: 'box',
  data() {
    return {
      str: '',
    }
  },
  props: {
    word: {
      type:String,
      default:''
    },
    sname:{
      type:String,
      default:'ls'
    }
  },
  watch: {
    str: function(newValue, oldValue) {
      //每当str的值改变则发送事件update:sname , 并且把值传过去,这时会修改父组件的data值
      this.$emit('update:sname', newValue);
      //如果多个值又不想用object,可以多次emit
      this.$emit('update:word', newValue+'1');
    }
  }
}
</script>
  
原文地址:https://www.cnblogs.com/llcdbk/p/11971951.html