sync属性修饰符

sync是组件通信方式的一种也可以实现父子数据的同步

看案例

父组件

<template>
  <div>
    小明的爸爸现在有{{ money }}元
    <h2>不使用sync修改符</h2>
    <Child :money="money" @update:money="money = $event"></Child>  //:money是父组件给子组件传递的props,@update是子组件绑定的自定义事件只不过名字叫做update:money,可以实现父子组件数据同步
  </div>
</template>
<script>
import Child from './Child.vue'
export default {
  data() {
    return {
      money: 10000
    }
  },
  components: {
    Child,
  }
}
</script>

子组件

<template>
  <div style="background: #ccc; height: 50px;">
    <span>小明每次花100元</span>
    <button @click="$emit('update:money',money - 100)">花钱</button>
    爸爸还剩 {{money}} 元
  </div>
</template>

<script type="text/ecmascript-6">
  export default {
    name: 'Child',
    props:['money']
  }
</script>

 

 

 在看使用sync

<template>
  <div>
    小明的爸爸现在有{{ money }}元
    <h2>不使用sync修改符</h2>
    <Child :money="money" @update:money="money = $event"></Child>
    <h2>使用sync修改符</h2>
<Child :money.sync="money"></Child> <hr /> </div> </template> <script> import Child from './Child.vue' import Child2 from './Child2.vue' export default { name: 'SyncTest', data() { return { money: 10000 } }, components: { Child, Child2 } } </script>

:money.sync含义:

  • 父组件给子组件传递了一个props叫money
  • 给当前子组件绑定了一个自定义事件,而且事件的名称即为update:money

 

posted @ 2021-12-20 17:26  keyeking  阅读(86)  评论(0编辑  收藏  举报