首页 > 其他 > 详细

子传父

时间:2021-09-01 23:07:53      阅读:22      评论:0      收藏:0      [点我收藏+]

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!