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">把学生给app</button>
</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>