子传父
1.子组件view
<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";
-
components挂载Views
-
在占位符中引用子组件的自定义事件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>来自子组件的值