v-model
可以实现双向绑定的效果,允许父组件控制子组件的显示/隐藏,同时允许子组件自己控制自身的显示/隐藏。以下是如何使用 v-model
实现这个需求:
在父组件中,你可以使用 v-model
来双向绑定一个变量,这个变量用于控制子组件的显示/隐藏:
<template>
<div>
<button @click="toggleChild">Toggle Child Component from Parent</button>
<ChildComponent v-model="showChild" />
</div>
</template>
<script>javascript">
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
showChild: false
};
},
methods: {
toggleChild() {
this.showChild = !this.showChild;
}
}
}
</script>
在子组件中,你需要定义一个名为 value
的 props
,以便接收来自父组件的 v-model
绑定:
<template>
<div>
<button @click="toggleSelf">Toggle Myself</button>
<div v-if="value">I'm the Child Component</div>
</div>
</template>
<script>javascript">
export default {
props: {
value: Boolean
},
methods: {
toggleSelf() {
// 子组件自己控制显示/隐藏状态
this.$emit('input', !this.value);
}
}
}
</script>
在子组件中,通过 this.$emit('input', ...)
来触发 input
事件,这将影响父组件中 v-model
的绑定值。这样,父组件和子组件都可以独立地控制显示/隐藏状态,实现了双向绑定的效果。