官方文档:https://uniapp.dcloud.io/vue-components?id=props
在父组件中赋值时加上 .sync,在子组件中使用 this.$emit(‘update:title’,“uni-app”)改变值
.sync 修饰符
当一个子组件改变了一个 prop 的值时,这个变化也会同步到父组件中所绑定。 .sync 它会被扩展为一个自动更新父组件属性的 v-on 监听器。
<!-- 父组件 -->
<template>
<view>
<syncA :title.sync="title"></syncA>
</view>
</template>
<script>
export default {
data() {
return {
title:"hello vue.js"
}
}
}
</script>
<!-- 子组件 -->
<template>
<view>
<view @click="changeTitle">{{title}}</view>
</view>
</template>
<script>
export default {
props: {
title: {
default: "hello"
},
},
methods:{
changeTitle(){
//触发一个更新事件
this.$emit('update:title',"uni-app")
}
}
}
</script>
本文档介绍了Vue组件中使用.sync修饰符来实现父子组件间双向数据绑定的方法。在父组件中,通过.sync附加到属性上,子组件通过$emit('update:属性名', 新值)触发更新事件,从而改变父组件的属性值。示例代码展示了如何在子组件中更改.sync修饰的title属性并同步到父组件。
1万+

被折叠的 条评论
为什么被折叠?



