【Vue】使用v

编程入门 行业动态 更新时间:2024-10-11 15:24:03

【<a href=https://www.elefans.com/category/jswz/34/1770550.html style=Vue】使用v"/>

【Vue】使用v

v-model 可以实现双向绑定的效果,允许父组件控制子组件的显示/隐藏,同时允许子组件自己控制自身的显示/隐藏。以下是如何使用 v-model 实现这个需求:

在父组件中,你可以使用 v-model 来双向绑定一个变量,这个变量用于控制子组件的显示/隐藏:

<template><div><button @click="toggleChild">Toggle Child Component from Parent</button><ChildComponent v-model="showChild" /></div>
</template><script>
import ChildComponent from './ChildComponent.vue';export default {components: {ChildComponent},data() {return {showChild: false};},methods: {toggleChild() {this.showChild = !this.showChild;}}
}
</script>

在子组件中,你需要定义一个名为 valueprops,以便接收来自父组件的 v-model 绑定:

<template><div><button @click="toggleSelf">Toggle Myself</button><div v-if="value">I'm the Child Component</div></div>
</template><script>
export default {props: {value: Boolean},methods: {toggleSelf() {// 子组件自己控制显示/隐藏状态this.$emit('input', !this.value);}}
}
</script>

在子组件中,通过 this.$emit('input', ...) 来触发 input 事件,这将影响父组件中 v-model 的绑定值。这样,父组件和子组件都可以独立地控制显示/隐藏状态,实现了双向绑定的效果。

更多推荐

【Vue】使用v

本文发布于:2023-11-30 14:28:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651227.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Vue

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!