Vue 中的 .sync 修饰符

162 阅读1分钟

Vue中的.sync修饰符一般用在需要外部传参(props)的时候,其功能是当子组件的props值发生变化时,也会同步到父组件上所绑定。

Vue规则

  • 组件不能修改props外部数据
  • $emit可以触发事件,并且传参
  • $event可以获取到$emit的参数

子组件代码:

<template>
  <div>
    {{money}}
    <button @click="$emit('update:money',money-100)">花钱</button>
  </div>
</template>

<script>
  export default{
    props:['money'],
  }
</script>

父组件:

<template>
  <div>
    {{total}}
    <hr/>
    <Child :money.sync="total"/>
  </div>
</template>

<script>
  import Child from 'Child.vue'
  export default {
    components:{Child},
    data(){
      return {total:10000}
    },
  }
</script>

语法糖 :money.sync="total"等价于 :mony="total" v-on:update:money="total = $event"