Vue3通过provide/inject为子组件注入key触发表单重挂载报错如何解决
报错原因
Vue3 已取消全局默认 Vue 导出,你代码中 import Vue from 'vue' 引入的变量为 undefined,调用 Vue.computed 自然会抛出找不到属性的错误。
修复方式如下:
从vue包中具名导入computed API,调用时不需要加Vue前缀:
<script lang="ts"> import { defineComponent, computed } from 'vue' export default defineComponent({ name: "App", provide() { return { routePath: computed(() => this.$route.path) } } }); </script>
方案可行性
你的实现逻辑本身是通顺的,修复上述导入错误后即可正常生效。但该方案冗余度较高,有两种更简便的实现方式可以替代:
- 全局路由配置:直接在路由出口绑定路由路径作为key,所有路由切换时都会自动重新挂载匹配到的组件
<router-view :key="$route.fullPath" />
- 表单组件单独配置:Patient组件本身可以直接访问路由实例,不需要额外通过provide/inject跨层传递路径,直接绑定key即可
<template> <form :key="$route.path"> ... </form> </template>
两种方式都可以实现路由切换时表单组件重新挂载、数据重新初始化的预期效果。
内容的提问来源于stack exchange,提问作者Kode Charlie
相关产品推荐
相关产品推荐

