SoFunction
Updated on 2025-04-04

Vue uses v-model to achieve the display and hidden effects of controlling subcomponents

v-modelThe effect of two-way binding can be achieved, allowing the parent component to control the display/hide of the child component, and allowing the child component to control its own display/hide. Here's how to use itv-modelTo achieve this requirement:

In the parent component, you can usev-modelTo bind a variable in both directions, this variable is used to control the display/hide of subcomponents:

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

In the child component, you need to define a name calledvalueofpropsto receive the parent componentv-modelBind:

&lt;template&gt;
  &lt;div&gt;
    &lt;button @click="toggleSelf"&gt;Toggle Myself&lt;/button&gt;
    &lt;div v-if="value"&gt;I'm the Child Component&lt;/div&gt;
  &lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
export default {
  props: {
    value: Boolean
  },
  methods: {
    toggleSelf() {
      // The child components control the display/hide status by themselves      this.$emit('input', !);
    }
  }
}
&lt;/script&gt;

In the subcomponent,this.$emit('input', ...)To triggerinputEvents, which will affect the parent componentv-modelbinding value. In this way, both the parent component and the child component can independently control the display/hide state, achieving the effect of two-way binding.

This is the article about Vue using v-model to implement the visual and hidden content of the subcomponents. For more related content of Vue control subcomponents, please search for my previous articles or continue browsing the relevant articles below. I hope everyone will support me in the future!