vuejs3 - vuejs 3:将密钥注入子组件?
问题描述
版本:
VueJS: 3.x
Chrome: Version 93.0.4577.63 (Official Build) (x86_64)
macOS: Big Sur 11.5.2
我的用例一定很常见,我有点惊讶它不能“开箱即用”。
我有这些简单的路线:
/patients/new
/patients/1
/about
我通过 vueJS 从单页应用程序 (SPA) 访问它router-link
:
<router-link to="/about">About</router-link> |
<router-link to="/patients/new">New Patient</router-link> |
<router-link to="/patients/1">Update Patient</router-link>
/patients/1
返回一个预填充的 HTML 表单,其中包含 ID 的患者详细信息1
。
/patients/new
返回具有空白条目的相同 HTML FORM。
直观地说,如果我访问/patients/1
链接,然后访问/patients/new
,我希望 HTML FORM 为空;相反,如果我访问/patients/new
and then /patients/1
,我希望 HTML FORM 会相应地预先填充。
这不是发生的事情。相反,SPA 不会重新创建/重新挂载 HTML 表单。
:key
解决方案:许多文章建议使用HTML FORM 中的属性引用的反应变量。然后无论我们访问哪个链接,只要我们更改响应变量,就应该重新创建/重新安装包含 HTML FORM 的 vueJS 组件。
我的方法: provide
根组件的反应变量,它在渲染 HTML FORMinject
的 vueJS 组件(即这里的组件)中。Patient
这是我的根组件的样子:
<script lang="ts">
import { defineComponent } from 'vue'
import Vue from 'vue'
export default defineComponent({
name: "App",
provide() {
return {
routePath: Vue.computed(() => this.$route.path)
}
}
});
</script>
其中反应变量是routePath
。然后在Patient
组件中,我有这个:
export default defineComponent({
name: "Patient",
inject: ['routePath'],
...
});
使用如下属性定义的 HTML FORM :key
:
<template>
<form :key="routePath">
...
</form>
</template>
我相信这里的基本想法是合理的,但它不起作用,而且看起来确实是一种麻烦的方法。
所以,这是我的问题:
- 这种方法合理吗?
- 为什么
Vue.computed()
调用被破坏了?这是来自 Chrome 控制台的堆栈跟踪:
App.vue?3acc:9 Uncaught TypeError: Cannot read properties of undefined (reading 'computed')
at Proxy.provide (App.vue?3acc:9)
at qe (runtime-core.esm-bundler.js:2463)
at Pr (runtime-core.esm-bundler.js:6713)
at Lr (runtime-core.esm-bundler.js:6632)
at Tr (runtime-core.esm-bundler.js:6562)
at D (runtime-core.esm-bundler.js:4421)
at N (runtime-core.esm-bundler.js:4396)
at m (runtime-core.esm-bundler.js:3991)
at K (runtime-core.esm-bundler.js:5140)
at mount (runtime-core.esm-bundler.js:3477)
感谢您调查它。
解决方案
看来这个问题在 vueJS 3.x 中没有解决。有关详细信息,请参阅未解决的问题。有变通办法。例如,请参阅这个 github 项目。就我而言,我决定更改工作流程以避免上述问题。
推荐阅读
- xml - 通过 SOAPUI 中的登录方法传递凭据时出现错误消息
- unity3d - 在着色器图中使用渐变填充不规则形状
- linux - Windows 的“/sys/class/net”等价物是什么
- swift - Swift 5 URLSession API 类抛出奇怪的错误
- javascript - 是否可以通过 HTML 按钮在我的机器上执行 python 脚本?
- java - 为什么有些服务器为同一个文件返回不同的内容长度?
- r - 在看不见的数据上测试 ml 模型时出错,尝试合并数据集或省略 na
- python - Python Scrapy 在第一个元素 csspath() 处停止并且不会抓取其余部分
- c# - 逐帧/逐样本播放时同步音频和视频播放
- excel - 如何将不同的临时值传递给触发的子程序?