错误
Uncaught TypeError: this.$refs.demo.$on is not a function
原因
Vue 3 中,$on 方法已经被移除,可能需要使用 addEventListener 方法替代。
错误代码
错误关键代码是: this.$refs.demo.$on("customEvent", this.getChildMsg);
<template>
<div class="container">
<h1>我是APP组件</h1>
<h2>{{ msg }}</h2>
<Demo ref="demo"></Demo>
</div>
</template>
import Demo from "./components/Demo.vue";
export default {
name: "APP",
components: {
Demo,
},
data() {
return {
msg: "",
};
},
mounted() {
this.$refs.demo.$on("customEvent", this.getChildMsg);
},
methods: {
getChildMsg(childMsg) {
console.info(childMsg);
this.msg = childMsg;
},
},
};
正确代码
正确关键代码是:addEventListener('customEvent', getChildMsg);
<template>
<div class="container">
<h1>我是APP组件</h1>
<h2>{{ msg }}</h2>
<Demo ref="demo" @customEvent="getChildMsg"></Demo>
</div>
</template>
import { ref } from "vue";
import Demo from "./components/Demo.vue";
export default {
name: "APP",
components: {
Demo,
},
setup(){
let msg=ref("")
function getChildMsg(chilMsg){
console.log(chilMsg);
msg.value=chilMsg
}
//关键代码
const demo=ref(null)
addEventListener('customEvent', getChildMsg);
return{
demo,getChildMsg,msg
}
}
};
注意:本文归作者所有,未经作者允许,不得转载