理解 Vue 的 .sync 修饰符

543 阅读1分钟

Vue 的 .sync 修饰符是用来对 prop 进行“双向绑定”设计的一种模式,以 update:myPropName 的模式, 通过 this.$emit 触发事件,向外传参。

使用代码如下:

<template>
	<div id="app">
        <div>{{money}}</div>
        <MyComponent :money.sync="money" />
    </div>
</template>
<script>
    import Vue from 'vue'
    
    Vue.component('myComponent', {
        template: '<div @click="updateMoney">点击</div>',
        props: ['money'],
        methods: {
            updateMoney() {
        		this.$emit('update:money', this.money - 100)
    		}
        }
    })
    
    export default {
        data() {
            return { money: 10000 },
        }
    }
</script>

:money.sync="money" 等价于 :money="money" @update:money="total = $event"$event 可以获取 $emit 的参数。

另外,Vue 文档 中提到几点需要注意的:

  1. 带有 .sync 修饰符的的 v-bind 不能和表达式一起使用(例如:money.sync="money + '!'" 是无效的)
  2. 我们用一个对象同时设置多个 prop 的时候,也可以将 .sync 修饰符和v-bind 配合使用。但是需要注意,将 v-bind.sync 用在一个字面量的对象上是无效的,例如 v-bind.sync="{ money }"