vue的子传父

子组件传值给父组件,需要触发一个事件。

在这个事件里,使用this.$emit("父组件使用的名称","子组件的数据")

在父组件中引用的子组件,在子组件的标签中用@父组件使用的名称="父组件里面的一个方法名($event)"

在父组件里使用刚刚定义的方法,父组件里面的一个方法名(data)

代码如下:

子组件代码:

<template>
<div>
  <!-- 定义一个事件,触发这个事件,才能传值给父组件 -->
    <button @click="trans()">点击按钮传递值</button>
     
</div>
</template>
<script>
export default {
  name: "Child",
  data () {
    return {
        childData:"childData"
    };
  },
  methods:{
      trans(){
        //this.$emit("父组件要触发的事件名称","需要传递的数据")
          this.$emit("transData",this.childData);
      }
  }
}
</script>
<style lang="css" scoped>
</style>

父组件代码:

<template>
<div>
    <!-- 父组件中引入子组件,定义一个方法,@子组件中$emit里的事件名,并传入$event -->
    <child @transData="getChildData($event)"></child>
    {{parentData}}
</div>
</template>
<script>
import Child from '../components/Child.vue'
export default {
  name: "Parent",
  components:{
      Child
  },
  data () {
    return {
        parentData:"parentData"
    };
  },
  methods:{
    //   实现父组件方法
      getChildData(data){
          this.parentData = data;
      }
  }
}
</script>
<style lang="css" scoped>
</style>
原文地址:https://www.cnblogs.com/luguankun/p/10600614.html