美文网首页
.sync 修饰符

.sync 修饰符

作者: Yandhi233 | 来源:发表于2021-12-09 17:25 被阅读0次

应用场景:组件获取 props 外部数据后,需要修改数据。

Vue 规定:
组件不能修改 props 外部数据;
$emit 可以触发事件,并且传参;
$event 可以获取 $emit 的参数。

示例:

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

点击 花钱
总结::money.sync = "total" 等价于 :money = "total" v-on:update:money = "total = $event".sync修饰符就是一个语法糖。

相关文章

网友评论

      本文标题:.sync 修饰符

      本文链接:https://www.haomeiwen.com/subject/zfiffrtx.html