子传父

时间:2021-08-30
本文章向大家介绍子传父,主要包括子传父使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.子组件view

子组件定义了一个click事件add点击来发送count值,并设置emit触发自定义事件numchange

<template>
 <div>
   <button @click="add()">+1</button>
 </div>
</template>
<script>
export default {
 data() {
   return {
     count: 0,
  };
},
 methods: {
   add() {
     this.count += 1;
     //   修改数据时,通过$emit()触发自定义事件
     this.$emit("numchange", this.count);
  },
},
};
</script>
<style scoped>
div {
 background-color: blueviolet;
}
</style>

2.父组件App.view

1.父组件需要import引入子组件的组件

import Views from "./views/views.vue";
  1. components挂载Views

  2. 在占位符中引用子组件的自定义事件numchange

      <views @numchange="getNewCount"></views>

    4.在methods方法中定义这个自定义事件的点击事件,

    val值是接受的子组件传递的this.count值

        getNewCount(val) {
        this.countFromson = val
      },

    App.vue

    getNewCount不需要加(),加括号后 methods中的getNewCount(val)是拿不到值得

<template>
 <div>
   <views @numchange="getNewCount"></views>
   <p>来自子组件的值{{countFromson}}</p>
 </div>
</template>
<script>
import Views from "./views/views.vue";
export default {
 data() {
   return {
     countFromson: 0,
  };
},
 components: {
   Views,
},
 methods: {
   getNewCount(val) {
     this.countFromson = val
  },
},
};
</script>
<style scoped>
</style>

 

原文地址:https://www.cnblogs.com/ajaXJson/p/15207310.html