在 Vue.js 中动态实例化组件

2022-01-21 00:00:00 components vue.js

按照本教程,我正在尝试以编程方式在我的页面上创建组件的实例.

Following this tutorial, I'm trying to programmatically create instances of a component on my page.

主要片段是这样的:

import Button from 'Button.vue'
import Vue from 'vue'
var ComponentClass = Vue.extend(Button)
var instance = new ComponentClass()
instance.$mount()
this.$refs.container.appendChild(instance.$el)

但是我得到两个错误:

  1. 我尝试实例化的组件包含对存储的引用,这些引用不起作用:TypeError: Cannot read property 'state' of undefined".

对于片段的最后一行 (this.$refs.container.appendChild(instance.$el)) 我收到此错误:"Uncaught TypeError: Cannot read未定义的属性‘容器’"

For the last line of the snippet (this.$refs.container.appendChild(instance.$el)) I get this error: "Uncaught TypeError: Cannot read property 'container' of undefined"

我真的不知道如何解决这个问题,如果任何 Vue.js 方面的强者可以给我一些提示,说明我为什么会遇到这些错误并解决它们,那将是非常棒的.

I'm really not sure how to troubleshoot this, if anyone strong in Vue.js could give me some hint as to why I'm getting these errors and to solve them that would be terrific.

推荐答案

1) 由于您手动实例化该组件并且它不属于您的主应用程序的组件树,因此不会自动将商店注入其中从你的根组件.当您实例化组件时,您必须手动将商店提供给构造函数..

1) Since you're manually instantiating that component and it doesn't belong to your main app's component tree, the store won't be automatically injected into it from your root component. You'll have to manually provide the store to the constructor when you instantiate the component ..

import ProjectRow from "./ProjectRow.vue";
import Vue from "vue";
import store from "../store";

let ProjectRowClass = Vue.extend(ProjectRow);
let ProjectRowInstance = new ProjectRowClass({ store });

2) 在 Vue 单文件组件 (SFC) 中,在默认导出 this 不引用 Vue 实例,因此您无权访问 $refs 或任何其他 Vue 实例属性/方法.要访问 Vue 实例,您需要将这一行 this.$refs.container.appendChild(instance.$el) 移动到默认导出中的某个位置,例如在 mounted 钩子或在你的 methods 之一内.

2) In a Vue Single File Component (SFC), outside of the default export this doesn't refer to the Vue instance, so you don't have access to $refs or any other Vue instance property/method. To gain access to the Vue instance you'll need to move this line this.$refs.container.appendChild(instance.$el) somewhere inside the default export, for example in the mounted hook or inside one of your methods.

请参阅此CodeSandbox,了解如何进行此操作的示例.

See this CodeSandbox for an example of how you may go about this.

相关文章