Vue中的sync修饰符

        sync是Vue中的一个修饰符,官方的意思是对prop进行的一个双向绑定。也就是说,sync修饰符的功能是:当一个子组件改变了一个来自外部(prop)的值时,这个值的变化也会绑定到父组件,使父组件中的值也进行更新。

        这里有一个例子能够帮助说明这一点,这里有一个Vue子组件: 

// 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>

        这个子组件接受一个来自外部的money变量,这个子组件的需求是,当点击按钮时,money数据改变的同时,也伴随着父组件数据的改变,但是这一点对于Vue本身来说是不允许的,因为Vue规定了子组件不能直接修改父组件的数据,会报错。
但是父组件用sync修饰符就可以很简单的做到这一点。

// App.vue

<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>

        这里父组件用sync监听到了子组件上数值的变化,并进行双向绑定,同时修改了父子组件中的数据。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue ,.sync 是一个语法糖,它能够简化父子组件之间的数据传递。.sync 修饰符实际上是一个双向绑定的简写形式,它会自动创建一个名为 update:propName 的自定义事件,并且在父组件监听这个事件,然后更新子组件的数据。 例如,在父组件使用子组件时,可以通过 v-bind.sync 修饰符将父组件的数据与子组件的数据绑定在一起: ``` <template> <ChildComponent :message.sync="messageFromParent"></ChildComponent> </template> ``` 这里的 .sync 修饰符会自动将子组件的 message 属性与父组件的 messageFromParent 属性进行双向绑定,并且在父组件监听名为 update:message 的自定义事件,以更新父组件的数据。 ``` <template> <ChildComponent :message.sync="messageFromParent"></ChildComponent> <button @click="updateMessage">Update Message</button> </template> <script> export default { data() { return { messageFromParent: 'Hello World' } }, methods: { updateMessage() { this.messageFromParent = 'Hello Vue' } } } </script> ``` 在子组件,可以通过 $emit() 方法触发 update:message 事件,以更新父组件的数据。 ``` <template> <div> <input type="text" v-model="message"> <button @click="$emit('update:message', message)">Update Message</button> </div> </template> <script> export default { props: { message: { type: String } } } </script> ``` 这样,父组件和子组件之间就可以通过 .sync 修饰符实现双向数据绑定了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值