<template>
<div>
<!-- 给 test组件实例对象绑定一个自定义事件,事件名称叫guigu,调用函数testFunction() -->
<test @guigu="testFunction()"></test>
<!-- 自定义事件的另一种书写方式 -->
<test_copy ref="school"></test_copy>
</div>
</template>
<script>
import test from './components/Test.vue';
import test_copy from './components/Test_copy.vue';
export default {
name: 'App',
components: {test,test_copy},
methods:{
testFunction(){
console.log("APP中的testFunction()函数被调用了")
},
mytip(){
alert("haha事件被触发了")
}
},
mounted(){
this.$refs.school.$on('haha',this.mytip)
}
}
</script>
<style>
</style>
想利用 ref 的方式来实现子组件与父组件之间的通信,用$on()绑定事件时,显示this.refs.school.$on不是一个函数,红色波浪线在$on下方,这种情况是什么问题?该如何解决?
首先,你应该把this.$ref.school这一整个实例打印出来,看下里面都有些什么属性跟方法,然后再往下进行
ervent.$on会有,this.$refs.school.$on不会有,前面一个event是vue实例所以有$on,而this.$refs.school子组件里面你没有定义$on
首先你要子组件中定义的有$on这个事件才会有