Vue中sync修饰符的使用

112 阅读1分钟

1. sync修饰符

假设有一个场景:

//app.vue
<template>  <div class="app">    App.vue 我现在有 {{total}}    <hr>    <Child :money="total" v-on:update:money="total = $event"/>  </div></template><script>import Child from "./Child.vue";export default {  data() {    return { total: 10000 };  },  components: { Child: Child }};</script>

//child.vue
<template>  <div class="child">    {{money}}    <button @click="$emit('update:money', money-100)">      <span>花钱</span>    </button>  </div></template><script>export default {  props: ["money"]};</script>

爸爸要给儿子钱,儿子要花钱,这怎么办?儿子可以通过触发事件向爸爸要钱。

之所以要通过触发事件来要钱是因为:

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

为了简化监听事件繁琐的代码v-on:update:money="total = $event ,尤大发明了.sync修饰符来简化代码。

<template>  <div class="app">    App.vue 我现在有 {{total}}    <hr>    <Child :money.sync="total"/>  </div></template>

vue 修饰符sync的功能是:当一个子组件改变了一个 prop 的值时,这个变化也会同步到父组件中所绑定。