Vue笔记-3

90 阅读1分钟

.sync修饰符的作用

  • 在某些情况下,需要对一个prop进行双向绑定,实现的方法是:子组件向父组件发送一个事件,父组件监听该事件,再更新prop。这时使用 .sync 修饰符可以实现子组件与父组件的双向绑定 & 子组件同步修改父组件的值。
  • 如下例子中:父组件传了一个参数 money 给子组件,子组件通过 $emit 修改 money 后,将值同步到父组件;使用修饰符 .sync 后,父组件中原<child :money="total" v-on:update:money="total = $event" /> 就可写为 <Child :money.sync="total"/>,简化了代码。
// 父组件
<template>
    <div class="app">
        现在有 {{total}}
        <Child :money.sync="total"/>
    </div>
</template>

<script>
    import Child from "./Child.vue";
    export default {
        data() {
            return { total: 10000 };
        },
        components: { Child: Child }
    };
</script>
//子组件
<template>
    <div class="child">
        {{money}}
        <button @click="$emit('update:money', money-100)">
            <span>花钱</span>
        </button>
    </div>
</template>

<script>
    export default {
        props: ["money"]
    };
</script>