博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Understand .sync in Vue
阅读量:5959 次
发布时间:2019-06-19

本文共 2367 字,大约阅读时间需要 7 分钟。

Preface

The first time I met .sync modifier, I didn't know it very well. So, I seldom use that. Today, I am going to get it.

Main

In the past, I use “two-way binding” like this:

parent component {

{parCount}}

let app = new Vue({  el: '#app',  data: {    parCount: 0  },  methods: {    add() {      this.parCount++    }  },  components: {    'button-counter': {      template:        '',      props: ['childCount'],      methods: {        add() {          this.$emit('add')        }      }    }  }})

It was easy to understand except a little inconvenient. I need to listen and handle event in child and parent component. Also

true two-way binding can create maintenance issues, because child components can mutate the parent without the source of that mutation being obvious in both the parent and the child.

So, Vue recommends emitting events in the pattern of update:myPropName. For example:

parent component {

{parCount}}

let app = new Vue({  el: '#app',  data: {    parCount: 0  },  methods: {},  components: {    'button-counter': {      template:        '',      props: ['childCount'],      methods: {        add() {          this.$emit('update:child-count', this.childCount + 1) // child-count is right while childCount won't work        }      }    }  }})

See? In this case, we don't have to add event callback in parent component because vue have done that. And this is the principle of .sync. For convenience, Vue offers a shorthand for this pattern with the .sync modifier which would make the code above like:

parent component {

{parCount}}

let app = new Vue({  el: '#app',  data: {    parCount: 0  },  methods: {},  components: {    'button-counter': {      template:        '',      props: ['childCount'],      methods: {        add() {          this.$emit('update:childCount', this.childCount + 1) // childCount is right while child-count won't work        }      }    }  }})

Also,

The .sync modifier can also be used with v-bind when using an object to set multiple props at once:

This passes each property in the doc object (e.g. title) as an individual prop, then adds v-on update listeners for each one.

For more information, go

转载地址:http://fwyax.baihongyu.com/

你可能感兴趣的文章
只要会营销,shi都能卖出去?
查看>>
sed单行处理命令奇偶行输出
查看>>
VC++深入详解学习笔记1
查看>>
安装配置discuz
查看>>
线程互互斥锁
查看>>
KVM虚拟机&openVSwitch杂记(1)
查看>>
win7下ActiveX注册错误0x80040200解决参考
查看>>
《.NET应用架构设计:原则、模式与实践》新书博客--试读-1.1-正确认识软件架构...
查看>>
2013 Linux领域年终盘点
查看>>
linux学习之查看程序端口占用情况
查看>>
相逢在栀枝花开的季节
查看>>
linux下git自动补全命令
查看>>
Ubuntu14.04LTS更新源
查看>>
Linux报“Unknown HZ value! (288) Assume 100”错误
查看>>
mysql多实例实例化数据库
查看>>
我的友情链接
查看>>
golang xml和json的解析与生成
查看>>
javascript 操作DOM元素样式
查看>>
Android 内存管理 &Memory Leak & OOM 分析
查看>>
【查找算法】基于存储的查找算法(哈希查找)
查看>>