Vue3:如何在Composable中实现Mixin式的Template Ref复用?
可行方案:用Composable替代全局Mixin获取Template Ref
完全可以实现,核心是在Composable中借助Vue的getCurrentInstance获取当前组件实例,再通过实例访问$refs,最后用计算属性封装起来,和原Mixin的逻辑对齐。
实现步骤
- 编写全局Composable文件
// globalComposable.js import { computed, getCurrentInstance } from 'vue'; export function useGlobalComposable() { // 获取当前组件实例 const instance = getCurrentInstance(); // 用计算属性封装template ref,和原Mixin逻辑一致 const myAlert = computed(() => { // 可选链避免实例不存在时报错 return instance?.$refs.myAlertDiv; }); return { myAlert }; }
- 在组件中使用
// App.vue <script setup> import { useGlobalComposable } from './globalComposable.js'; import { onMounted } from 'vue'; const { myAlert } = useGlobalComposable(); onMounted(() => { // 直接访问myAlert.value(因为是computed响应式对象) console.log(myAlert.value); }) </script> <template> <!-- 必须存在对应ref的元素,否则myAlert会是undefined --> <div ref="myAlertDiv">这是alert容器</div> </template>
关键注意事项
- 组件模板中必须有
ref="myAlertDiv"的元素,否则myAlert.value会返回undefined。 getCurrentInstance只能在组件的setup阶段或Composable内部调用,不能在异步回调等外部上下文使用。- 用
computed包裹可以保证myAlert始终响应$refs的变化(比如动态渲染的元素)。
内容的提问来源于stack exchange,提问作者Sc00rpY
相关产品推荐
相关产品推荐

