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

    使用代码如下:

    1. <template>
    2. <div id="app">
    3. <div>{{money}}</div>
    4. <MyComponent :money.sync="money" />
    5. </div>
    6. </template>
    7. <script>
    8. import Vue from 'vue'
    9. Vue.component('myComponent', {
    10. template: '<div @click="updateMoney">点击</div>'
    11. props: ['money'],
    12. methods: {
    13. updateMoney() {
    14. this.$emit('update:money', this.money - 100)
    15. }
    16. }
    17. })
    18. export default {
    19. data() {
    20. return { money: 10000 },
    21. }
    22. }
    23. </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 }"