vue中 .sync 修饰符 个人理解

vue中.sync修饰符有什么用

.sync 修饰符 其实就是一个语法糖

  • vue中 :子组件不能修改props 外部数据
  • vue中: $emit 可以触发事件并传参
  • vue中: $event可以获取 $emit 的参数

好,明白这些之后 场景实现
父组件 parent 有自己的data状态 money 100
父组件中有子组件 child 想把data中的状态给子组件
代码实现

<child :money="money"></child>

// 子组件中有一个button 按钮 每次点击之后 父组件中的data 状态中 money 就要-10 块钱 怎么实现??????
<child :money="money" @handleClick="handleClick"></child>
// 子组件中button 按钮 
<button @click="handleClick1"></button>
methods:{
	handleClick1(){
	this.$emit("handleClick",money - 10)
	}
}
// 之后 父组件 再去定义 handleClick方法去接受 
// 这种最基本的父子传值方法是不是挺复杂的

下面就是上面代码的优化结果

<child :money="money" ></child>
// 子组件中button 按钮点击事件
<button @click="$emit('updata:money', money - 10)"></button>
// 父组件中
<child :money="money" v-on:updata:money="money = $event"></child>

可以看到上面的方法都是通过监听事件 去通知父组件去修改 子组件不能直接修改
接下来就是 .sync修饰符的作用

<child :money.sync="money"></child>
// 相当于 <child :money="money" v-on:updata:money="money = $event "></child>

// 当然子组件还是要有事件去触发
<button @click="handleClick"></button>
methods:{
	handleClick(){
	this.$emit("updata:money",money-10)
	}
}

大概就是这么多,欢迎补充

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 修饰符实现双向数据绑定了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王哥是真漂酿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值