vue的组件自定义事件,提示我说this.$refs.student.$on is not a function,是哪里出现了问题
下面是我的app代码和student代码:
// App.vue
<template>
<div class="app">
<h1>{{ msg }}h1>
<School :getSchoolName="getSchoolName" />
<hr />
<Student ref="student" />
div>
<hr />
<img alt="Vue logo" src="./assets/logo.png" />
<HelloWorld msg="Welcome to Your Vue.js App" />
template>
<script>
import HelloWorld from "./components/HelloWorld.vue";
import School from "./components/School.vue";
import Student from "./components/Student.vue";
export default {
name: "App",
data() {
return {
msg: "this is hello vue",
};
},
methods: {
getSchoolName(name) {
console.log("app 接受了学校名 ", name);
},
getStudentName(name) {
console.log('app 接受了学生姓名 ', name);
}
},
components: {
HelloWorld,
School,
Student,
},
mounted() {
setTimeout(() => {
this.$refs.student.$on('atguigu', this.getStudentName)
}, 20);
},
};
script>
<style>
.app {
height: auto;
width: 50%;
background-color: blueviolet;
padding: 10px;
}
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
style>
<template>
<div class="student">
<h2>学生姓名:{{name}}h2>
<h3>学生性别: {{sex}}h3>
<button @click="sendStudentName">把学生给appbutton>
div>
template>
<script>
export default ({
name: 'Student_vue',
data() {
return {
name: 'mac',
sex: 'man'
}
},
methods: {
sendStudentName() {
// 触发student实例身上的硅谷事件
this.$emit('atguigu', this.name);
}
}
})
script>
<style scoped>
.student {
background-color: teal;
padding: 5px;
margin-top: 10px;
}
style>
vue3与vue2语法不一样
打印一下 this.$refs.student 看看 有没有 $on方法
1.父组件(APP)
首先你要明白 $on 是什么,他应该不是 student 子组件的一个方法把,它应该是全局事件总线的 eventBus,我看你的写法就是 监听 eventBus 上的 “atguigu”事件;
2. 子组件(Student)
你子组件写的又是正常的触发父组件的方法,和父组件的 监听也没有任何关系;如果你父组件用 EventBus 的写法 应该是父组件监听 this.$eventBus.on("atguigu"), 然后子组件去触发 this.$eventBus.emit("atguigu",this.name);
以上是一个完整的事件车的通信
export default ({
name: 'Student_vue', -》name: 'Student',