Vue child component passes value demo to parent component

 Child component passes value to parent component

1. The child component passes information to the parent component through a custom event

      <button @click="sendFather">Send data to dad</button>

2. The parent component listens to the events of the child component

    <child-my @sonData="getSonData"></child-my>

Summary: child components pass values ​​to parent components

The child component triggers a custom event and the parent component listens to the custom event at the same time. When the child component triggers a custom event, the custom event will be thrown to the parent component. When the parent component triggers the custom event, the corresponding event will be executed.

Dad page code:

<template>
  <div class="my-parent" style="background:#fff">
    <h3>我是父组件</h3>

    <p>爸爸的数据</p>
    <ul>
      <li>钱财:{
   
   {fatherData.money}}</li>
      <li>工作:{
   
   {fatherData.job}}</li>
    </ul>
    <p>显示一下儿子给爸爸的数据</p>
    <ul>
      <li>{
   
   {sunData.joy}}</li>
      <li>{
   
   {sunData.fly}}</li>
    </ul>

    <child-my :fatherData='fatherData' @sonData="getSonData"></child-my>
  </div>
</template>

<script>
import childMy from "../../../../common/child-my.vue";
export default {
  components:{childMy},
  data(){
    return{
      fatherData:{
        money:100000000,
        job:'程序员'
      },
      sunData:{}
    }
  },
  methods:{
    getSonData(obj){
        console.log(obj)
        this.sunData=obj
    }
  }
};
</script>

Son page code:

<template>
  <div class="my-child">
    <h3>我是子组件</h3>

    <p>儿子的数据:都是玩具</p>
    <ul>
      <li>{
   
   {childData.joy}}</li>
      <li>{
   
   {childData.fly}}</li>
    </ul>

    <div>
      <button @click="sendFather">发送给爸爸数据</button>
    </div>

    <br>
    <br>
    <br>
   

    儿子继承爸爸的钱财

    <p>{
   
   {fatherData.money}}</p>
  </div>
</template>

<script>
export default {
  data() {
    return{
      childData:{
        joy:'变形金刚',
        fly:'直升机'
      }
    }
  },
  props:{
    fatherData:Object
  },
  methods:{
    sendFather(){
      this.$emit("sonData", this.childData);
    }
  }
};
</script>

Summary: The key code for the son page to pass the value to the father page

Well, done, straightforward and clear novice-level code. Don't Tucao Daniel

Guess you like

Origin blog.csdn.net/taotaobaobei/article/details/111667117