首页 > 解决方案 > 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/newand 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>

我相信这里的基本想法是合理的,但它不起作用,而且看起来确实是一种麻烦的方法。

所以,这是我的问题:

  1. 这种方法合理吗?
  2. 为什么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)

感谢您调查它。

标签: vuejs3

解决方案


看来这个问题在 vueJS 3.x 中没有解决。有关详细信息,请参阅未解决的问题。有变通办法。例如,请参阅这个 github 项目。就我而言,我决定更改工作流程以避免上述问题。


推荐阅读