vue的.sync修饰符用法及原理详解

vue .sync的历史

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


vue 修饰符sync的功能是:当一个子组件改变了一个 prop 的值时,这个变化也会同步到父组件中所绑定。如果我们不用.sync,我们想做上面的那个弹窗功能,我们也可以props传初始值,然后事件监听,实现起来也不算复杂。这里用sync实现,只是给大家提供一个思路,让其明白他的实现原理,可能有其它复杂的功能适用sync。
 

假如父组件传给子组件的值,子组件接受之后,想要改变父组件传过来的值,就可以使用sync

father.vue

<template>
<div class="LightEnergy">
   <p>这是父组件的内容 :{{name}}</p>
   <p style="height:60px;margin-top:60px">
    <child :name.sync=name></child>
   </p>
</div>
</template>

<script>
import child from './components/child.vue'
export default {
  name: "LightEnergy",
  data() {
    return {
      name:'hello',
      options: options
    };
  },
  components: {
    child
  },
  methods: {
  },
  mounted() {
  },
  destroyed(){
    clearInterval(t)
  }
};

child.vue

<template>
  <div id="childCon">
    <el-row>
        子组件接受父组件的值{{name}}
      <el-button type="success" @click="upCon">成功按钮</el-button>
    </el-row>
  </div>
</template>

<script>
export default {
  name: "childCon",
  data() {
    return {};
  },
  props: ['name'],
  methods: {
      upCon(){
          this.$emit('update:name', '新的name值')
      }
  }
};
</script>

<style scoped>
</style>

vue .sync修饰符的使用详解​www.jb51.net/article/142099.htm

2.双向数据绑定,子组件改变的时候,父组件也在改变

father.vue

<template>
  <div class="hello">
    父级的内容<input type="text" v-model="wrd">
    <br /><br />
    <box :word.sync="wrd"></box>
  </div>
</template>
<script>
import box from "./components/child"; //引入box子组件
export default {
  name: "HelloWorld",
  data() {
    return {
      wrd: ""
    };
  },
  components: {
    box
  }
};
</script>
<style scoped></style>

child.vue

<template>
  <div class="hello">
    <div class="ipt">
     子级的内容 <input type="text" v-model="str">
    </div>
    <h2>{{ word }}</h2>
  </div>
</template>
<script>
export default {
  name: "box",
  data() {
    return {
      str: ""
    };
  },
  props:['word'],
  watch: {
    str: function(newValue, oldValue) {
        console.log(newValue)
        console.log(oldValue)
      //每当str的值改变则发送事件update:word , 并且把值传过去
      this.$emit("update:word", newValue);
    }
  }
};
</script>
  • 15
    点赞
  • 54
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值