相信刚上手 vue3的你一定会遇到各种小问题,下面给大家分享一个小的点。希望能为遇到相同问题的你快速解决问题!
首先在 vue2.x 以及 vue3.x 的配置写法时 可以正常使用 this.$parent 访问父组件,但是在 vue3.x setup(props, ctx) 中 只能拿到 ctx.attrs、ctx.emit 和 ctx.slots。要想调用父组件的方法,我们需要用 provide & inject 来实现:
1.在父组件中 提供组件 ref 以及 提供需要的 function
// parent component
<template>
<div ref="root">parent</div>
</template>
<script setup>
import { provide, ref } from 'vue';
// 父组件 ref 引用
export const root = ref(null);
export function testFun() {
console.log('parent/testFun')
}
const PARENT_PROVIDE = 'parentProvide'
// 提供父组件 ref 引用
provide(PARENT_PROVIDE, root);
// 提供父组件指定方法
provide(`${PARENT_PROVIDE}/testFun`, testFun);
</script>
2.在子组件中 inject
<template>
<div>child<div>
</template>
<script setup>
import { inject, onMounted } from 'vue';
const PARENT_PROVIDE = 'parentProvide'
onMounted(() => {
// 注入父组件 ref
const parent = inject(PARENT_PROVIDE);
console.log('parent root:' parent);
// 注入父组件指定方法
const parentTestFun = inject(`${PARENT_PROVIDE}/testFun`);
parentTestFun();
})
</script>
3.进阶优化
如果是组件库 或者 长期维护的项目 建议使用 一个公共的 Symbol 保存常量
// provide-symbol
export const PARENT_SYMBOL = Symbol();
最终我们可以较为方便的在 setup 中迁移 vue2 原有逻辑。同样 vue3这样的设计也可以减少不必要暴露的组件方法。
--------据说99.99%的人点赞这篇文章的程序员,写的代码都没有 BUG--------