在vue2.x 中使用“ p a r e n t ” 层 级 关 系 寻 找 父 组 件 然 后 调 用 父 组 件 方 法 在 本 地 开 发 没 有 问 题 , 但 是 打 包 后 就 会 报 “ parent”层级关系寻找父组件然后调用父组件方法在本地开发没有问题,但是打包后就会报“ parent”层级关系寻找父组件然后调用父组件方法在本地开发没有问题,但是打包后就会报“parent”错,打印ctx发现没有这个属性,但是现在是用vue3开发的项目,所以开始研究其他方法,如下就是一种可行得通的方法,如果有其他方法可以一起讨论呦,下面一起看看使用方法:
在子组件中通过$emit()调用父组件的方法。
先看官方emit()原型:
vm.emit( eventName, […args] )
vm.$emit( eventName, […args] )
参数:
{
string} eventName
[…args]
触发当前实例上的事件。附加参数都会传给监听器回调。
子组件:注意emits和setup(props,{emit})
<template>
<button @click="handleClick">触发父组件方法</button>
</template>
<script>
export default {
name: "childrenComponent",
emits: ['childToParent'],
setup(props,{
emit}){
const handleClick = ()=>{
emit('childToParent',"传递消息")
}
return{
handleClick
}
}
}
</script>
父组件:正常接收就行
<template>
<childrenComponent @childToParent="childToParent"></childrenComponent>
</template>
<script>
import childrenComponent from './childrenComponent.vue'
export default {
name: "parentComponent",
components:{
childrenComponent},
setup(props){
const childToParent = (msg)=>{
console.log(msg)
}
return{
childToParent
}
}
}
</script>
另一种写法:
子组件,在script标签加上 ts(typescript), setup语法糖
<template>
<button @click="handleClick">触发父组件方法</button>
</template>
<script lang="ts" setup>
const emit = defineEmits(['childToParent']);
const handleClick = ()=>{
emit('childToParent',"传递消息")
}
</script>
父组件
<template>
<childrenComponent @childToParent="childToParent"></childrenComponent>
</template>
<script lang="ts" setup>
const childToParent = (msg)=>{
console.log(msg)
}
</script>