使用uniapp实现父组件调用子组件方法时报错:[Vue warn]: Invalid vnode type when creating vnode: null.
实现代码如下:
子组件:
<template><view><view class="toolsHeader"><view class="toolsTitle">{{toolsName}}</view><uni-icons :type="collectType" @click="collection"></uni-icons></view></view>
</template><script setup>
import { ref,defineEmits,defineExpose } from 'vue';const emit = defineEmits(['collect','refresh'])
const collectType = ref('star');const props = defineProps({toolsName:{type: String,default: ''}
});const changeStatus = (tar, status)=>{if(tar == 'collect'){collectType.value = status == 1 ? 'star-filled' : 'star';}
}defineExpose({changeStatus
})const collection = ()=>{let toStatus = collectType.value == 'star' ? 1 : 0;emit("collect", toStatus);
}</script><style lang="scss" scoped>
</style>
父组件:
<template><view><tools-header ref="toolsHeader" toolsName="name" @collect="collectools"></tools-header></view>
</template><script setup>
import { ref } from 'vue';const toolsHeader = ref({});const collectools = (status)=>{toolsHeader.value.changeStatus('collect', status);
}
</script><style lang="scss" scoped></style>
运行项目就报如上报警:[Vue warn]: Invalid vnode type when creating vnode: null.
经过一番查询和尝试,发现是ref和组件名冲突了,虽然这里ref使用的是驼峰格式,组件名是-分隔,但底层应该是将tools-header转换成了toolsHeader,导致了名称冲突。修改下ref名称即可:
<template><view><tools-header ref="toolsHeaderChild" toolsName="name" @collect="collectools"></tools-header></view>
</template><script setup>
import { ref } from 'vue';const toolsHeaderChild= ref({});const collectools = (status)=>{toolsHeaderChild.value.changeStatus('collect', status);
}
</script><style lang="scss" scoped></style>
再次运行,结果正常。
参考文章:
https://www.cnblogs.com/lpkshuai/p/17176606.html
nuxt3 Vue 3 报错 Invalid vnode type when creating vnode:null_invalid vnode type when creating vnode: null.-CSDN博客