Detailed explanation of father and son passing parameters in vue

Parent-child parameter passing in vue

In Vue, the parent component needs to use props to pass data to the child component, and the child component receives the data passed by the parent component through props. This method is a one-way data flow, and the parent component can pass new values ​​to the child component by modifying the props data.

1. The parent component passes static data to the child component
Use v-bind or the shorthand symbol ":" in the parent component to bind the data to the props property of the child component, for example:

<template>
  <div>
    <child-component message="Hello, Vue!" />
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
    
    
  components: {
    
    
    ChildComponent
  }
};
</script>

Define the props attribute in the child component to receive the data passed by the parent component:

export default {
    
    
  props: {
    
    
    message: {
    
    
      type: String,
      required: true
    }
  }
};

2. The parent component dynamically transfers data to the child component
If you need to dynamically transfer data, you can bind the data of the parent component to the props attribute of the child component, and then modify the data in the parent component to trigger the update of the child component data. For example:

<template>
  <div>
    <button @click="changeMessage">Change Message</button>
    <child-component :message="parentMessage" />
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
    
    
  components: {
    
    
    ChildComponent
  },
  data() {
    
    
    return {
    
    
      parentMessage: 'Hello, Vue!'
    };
  },
  methods: {
    
    
    changeMessage() {
    
    
      this.parentMessage = 'Hello, Vue3!';
    }
  }
};
</script>

Define the props attribute in the child component to receive the data passed by the parent component:

export default {
    
    
  props: {
    
    
    message: {
    
    
      type: String,
      required: true
    }
  }
};

It should be noted that when the parent component modifies the props data, the child component will also be re-rendered. If you don't want the child component to be affected, you can copy the props data to the child component's data, and then use data in the child component to manipulate the data.

Guess you like

Origin blog.csdn.net/weixin_45357661/article/details/130457128