Vue .sync 简述

110 阅读1分钟

.sync修饰符

image.png

App.vue

<template>
  <div class="app">
    App.vue 我现在有 {{total}}
    <hr>
    <Child :money.sync="total" />
      // .sync 就是下面的语法糖相当于缩写把
    <!-- <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>

<style>
.app {
  border: 3px solid red;
  padding: 10px;
}
</style>

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>


<style>
.child {
  border: 3px solid green;
}
</style>

app.vue 中的 event是会拿到child.vue中的event 是会拿到 child.vue中的 emit 返回的值

总结

sync 翻译出来是"同步"意识.对你已经理解了大半,就是子组件的事件修改了值,你要通知一声你的父组件我改值了你要跟我一样哦. sync也是语法糖(缩写) :@update:money="total = $event" .