Vue中.sync的用法

vue提供了.sync修饰符,说白了就是一种简写的方式,我们可以将其当作是一种语法糖,比如v-on: click可以简写为@click。

sync修饰符,与我们平常使用$emit实现父子组件通信没有区别,只不过是写法上方便一些。

日常开发时,我们总会遇到需要父子组件双向绑定的问题,但是考虑到组件的可维护性,vue中是不允许子组件改变父组件传的props值的。

那么同时,vue中也提供了一种解决方案.sync修饰符。在此之前,希望你已经知道了vue中是如何通过事件的方式实现子组件修改父组件的data的。

子组件使用$emit向父组件发送事件:

this.$emit('update:title', newTitle)

父组件监听这个事件并更新一个本地的数据title:

<text-document
  :title="title"
  @update:title="val => title = val"
></text-document>

为了方便这种写法,vue提供了.sync修饰符,说白了就是一种简写的方式,我们可以将其当作是一种语法糖,比如v-on: click可以简写为@click。

而上边父组件的这种写法,换成sync的方式就像下边这样:

<text-document
  :title.sync="title"
></text-document>

有没有发现很清晰,而子组件中我们的写法不变,其实这两种写法是等价的,只是一个语法糖而已,如果到这里你还不太明白。

下边是个完整的demo,可以copy自己的项目中尝试一下。相信你会恍然大悟。

Father.vue

<template>
  <div>
    <child :name.sync="name"></child>
    <button @click="al">点击</button>
    <button @click="change">改变</button>
  </div>
</template>
 
<script>
import child from './Child'
export default {
  name: 'list',
  components: {
    child
  },
  data () {
    return {
      name: 'lyh'
    }
  },
  methods: {
    al() {
      alert(this.name)
    },
    change() {
      this.name = '123'
    }
  }
}
</script>

Child.vue

<template>
  <div>
    <input :value="name" @input="abc" type="text">
  </div>
</template>
<script>
  export default {
    props: {
      name: {
        type: String,
        required: true
      }
    },
    methods: {
      abc(e) {
        console.log(e.target.value)
        this.$emit('update:name', e.target.value)
      }
    }
  }
</script>

 

posted @ 2021-12-03 16:22  罗毅豪  阅读(5081)  评论(0编辑  收藏  举报