vue.js - VueJS - 按名称以编程方式创建组件
问题描述
我正在尝试构建一个动态 Vue 系统,我想在其中插入只知道它们的名称的自定义组件。来自这里的灵感带我去做:
export default {
name: 'MySite',
mixins: [MyMixin],
components: {MyComponent1, MyComponent2},
...
}
...
mounted() {
var ComponentClass = Vue.extend(MyComponent1)
var instance = new ComponentClass()
instance.$mount() // pass nothing
this.$refs.container.appendChild(instance.$el)
}
现在我想做同样的事情,但只知道组件名称“MyComponent1”为字符串。有什么办法呢?我想它与纯 JavaScript 的关系比 Vue 更重要,但我不知道该怎么做。
解决方案
你说得对是一个简单的js。
看下面的例子,最重要的是eval()
class Polygon {
constructor(height, width) {
this.height = height;
this.width = width;
}
get getHeight() {
return this.height
}
}
// js string code
var code = "new Polygon(15, 200)";
// convert it to code;
var cls = eval(code);
console.log(cls.getHeight)