vue3中v-model父子组件双向数据绑定
原创
©著作权归作者所有:来自51CTO博客作者wx58f59a601fad5的原创作品,请联系作者获取转载授权,否则将追究法律责任
父组件 Comp1
<template>
<div class="border red">
{{username}} / {{password}}
<Comp2 v-model:username="username" v-model:password="password" />
</div>
</template>
<script>
import Comp2 from "./Comp2.vue";
export default {
components: { Comp2 },
data() {
return {
username: 'adleytales',
password: ''
}
}
};
</script>
子组件 Comp2
<template>
<div class="border blueviolet">
用户名: <input type="text" v-model="username" @input="changeUsername" />
<br />
密码: <input type="password" v-model="password" @input="changePassword" />
</div>
</template>
<script>
export default {
props: {
username: String,
password: String,
},
data() {
return {
username: "",
password: "",
};
},
methods: {
changeUsername() {
this.$emit("update:username", this.username);
},
changePassword() {
this.$emit("update:password", this.password);
},
},
};
</script>