以前学过:通过父组件给子组件传递函数类型的props实现:子给父传递数据
新学:通过父组件给子组件绑定一个自定义事件实现:子给父传递数据
<div>
<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据 -->
<!-- Students绑定了gain事件,要想触发事件,只能在Students组件操作,
事件触发后执行getStudentsName函数方法-->
<Students v-on:gain="getStudentsName"></Students>
</div>
export default {
name: "App",
components: {Students,},
methods: {
//...a是什么意思? 除了name以外的数据,剩余的全部数据用数组展示
getStudentsName(name, ...a) {
console.log("App获取到了" + name + a); //APP获取到了 万万[1,2,3]
},
},
};
<template>
<div>
<h2>{{ name }}</h2>
<button @click="sendStudentsName">把学生名给App</button>
</div>
</template>
export default {
name: "Students",
data() {
return {
name: "万万",
a: 1,
b: 2,
c: 3,
};
},
methods: {
sendStudentsName() {
//触发Students组件实例身上的gain事件($emit有触发事件的作用)
//事件后面加的就是想要传递的数据,可以传递多个
this.$emit("gain", this.name, this.a, this.b, this.c);
},
},
};
组件上绑定原生DOM事件:需要使用native修饰符
//此时点击Students组件,不会显示弹窗,会把click当成一个自定义事件处理
<Students v-on:gain="getStudentsName" @click="show"></Students>
methods: {
show() {
alert("666");
},
}
//只需添加一个native在组件即可解决,跳出弹窗
<Students v-on:gain="getStudentsName" @click.native="show"></Students>