SoFunction
Updated on 2025-04-05

Principles and implementation methods of parent-child component parameters Original

In Vue, data transfer between parent and child components is often implemented using props. The specific principle is that when a parent component nests a child component, props are used inside the child component to receive data passed from the parent component. These data can be basic types such as strings, numbers, etc., or complex types such as objects or arrays.

Here is an example of how to pass values ​​to children and update counter operations in parent components through a simple counter component:

Subcomponents:

<!--  -->
<template>
  <div class="counter">
    <h4>{{ title }}</h4>
    <p>Current count:{{ count }}</p>
    <button @click="addCount">+1</button>
    <button @click="reduceCount">-1</button>
  </div>
</template>

<script>
export default {
  name: "Counter",
  props: {
    title: {
      type: String,
      required: true,
    },
    count: {
      type: Number,
      required: true,
    },
  },
  methods: {
    // Add count    addCount() {
      this.$emit("add-count");
    },
    // Decrease count    reduceCount() {
      this.$emit("reduce-count");
    },
  },
};
</script>

Parent component:

<!--  -->
<template>
  <div class="container">
    <h2>Counter Application</h2>
    <hr />
    <!-- The parent component passes the counter title and current count to the child component -->
    <Counter :title="title" :count="count" @add-count="handleAddCount" @reduce-count="handleReduceCount" />
  </div>
</template>

<script>
import Counter from "./components/";

export default {
  name: "App",
  components: {
    Counter,
  },
  data() {
    return {
      title: "counter",
      count: 0,
    };
  },
  methods: {
    // Add count    handleAddCount() {
      ++;
    },
    // Decrease count    handleReduceCount() {
      --;
    },
  },
};
</script>

In the above example, the way to pass data is to bind the data to the props property of the child component by using the v-bind directive in the parent component and accessing the props to receive data inside the child component. At the same time, two methods addCount and reduceCount are defined inside the child component to trigger custom events and emit events to the parent component.

Finally, it should be noted that the data flow between parent and child components is unidirectional, that is, the data can only flow from the parent component to the child component, and cannot be reversed. If the child component wants to modify the data, the parent component must be notified through the emit event to perform the corresponding operation.