In vue, the parent-child component passes the value, how to modify the value of the parent component in the child component?

In Vue, parent-child components pass values, how to modify the value of parent components in child components?

Answer: 1. When a child component wants to modify, it needs to send a custom event via **$emit**. After the parent component receives it, the parent component will modify it. 2.
When the prop you pass in is Object type or Array At this time, modifying the prop inside the child component can change the value in the parent component accordingly (objects and arrays are reference types, pointing to the same memory space)

1. Use the event dispatched by $emit

**1)、*子组件向父组件传递数据
$emit的理解:当我们点击按钮,子组件便会分发一个名为output的事件,父组件中使用函数接收该事件传递的数据。**

**父组件**

<template>
  <div>
    <p>{
    
    {
    
    initVal}}</p>
    <Son ref="son" :fatherData='outputVal' @ouput='getSonVal'/>
  </div>
</template>

<script>
import Son from "./son";
export default {
    
    
  name: "father",
  data() {
    
    
    return {
    
    
      initVal:'这是父组件自身的值'
    };
  },
  components:{
    
    
    Son
  },
  methods: {
    
    
    getSonVal(val){
    
    
      this.initVal=val
    }
  }
};
</script>

<style>
</style>

**子组件**

<template>
  <div>
    <el-button @click="ouputToFather">子组件中的按钮</el-button>
  </div>
</template>

<script>
export default {
    
    
  name: "Son",
  data() {
    
    
    return {
    
    
      outSonVal:'我是子组件传递给父组件的数据'
    };
  },
  methods: {
    
    
    ouputToFather(){
    
    
      this.$emit('ouput',this.outSonVal)//分发名为output的事件,将outSonVal的值发送出去
    }
  }
};
</script>

<style>
</style>

insert image description here
reference documents

1.https://www.jb51.net/article/142021.htm
2.http://www.javashuo.com/article/p-macfeagd-ca.html
3.https://blog.csdn.net/u010640592/article/details/123007042

Guess you like

Origin blog.csdn.net/qq_44552416/article/details/127496886