Vue.js 2:如何从.vue文件初始化(构造)Vue组件? [英] Vue.js 2: How to initialize(construct) a Vue component from a .vue file?

查看:314
本文介绍了Vue.js 2:如何从.vue文件初始化(构造)Vue组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个Component实例:

I'm trying to create a Component instance:

import MyComponent from './components/MyCompnent.vue';
export default {
    mounted() {
        // The following line fails.
        const vm = new MyComponent();
        vm.$mount('#some-place');
    }
}

new行报告错误:

未捕获的TypeError:MyComponent.default不是构造函数

Uncaught TypeError: MyComponent.default is not a constructor

那我要如何创建组件呢?

So how if I want to create the component?

推荐答案

最后,我自己找到了解决方案,非常简单:

Finally, I found the solution myself, very simple:

导入的Component本身不是构造函数,但是我们可以轻松地构造一个构造函数:

The Component imported itself is not a constructor, but we can easily make a constructor:

import MyComponent from './components/MyCompnent.vue';
const MyComponentConstructor = Vue.extend(MyComponent);

所以最终的解决方案是:

So the final solution is:

import MyComponent from './components/MyCompnent.vue';
export default {
    mounted() {
        const MyComponentConstructor = Vue.extend(MyComponent);
        const vm = new MyComponentConstructor();
        vm.$mount('#some-place');
    }
}

这篇关于Vue.js 2:如何从.vue文件初始化(构造)Vue组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆