简体   繁体   English

Vue.js 2:如何从 .vue 文件初始化(构造)一个 Vue 组件?

[英]Vue.js 2: How to initialize(construct) a Vue component from a .vue file?

I'm trying to create a Component instance:我正在尝试创建一个组件实例:

App.vue

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

and the new line reports an error:并且new行报错:

Uncaught TypeError: MyComponent.default is not a constructor未捕获的 TypeError:MyComponent.default 不是构造函数

So how if I want to create the component?那么如果我想创建组件呢?

Finally, I found the solution myself, very simple:最后,我自己找到了解决方案,非常简单:

The Component imported itself is not a constructor, but we can easily make a constructor:导入的Component本身不是构造函数,但我们可以很容易地做一个构造函数:

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');
    }
}

Following is the way to register a component inside other component:以下是在其他组件中注册组件的方法:

export default {
  el: '#some-place'
  components: {
      'my-component'
  }
}

Documentation: link文档: 链接

Edited: How to create vm instance编辑:如何创建虚拟机实例

If you want to initialise the vm instance, you can do it using Vue.extend .如果要初始化 vm 实例,可以使用Vue.extend来完成。 What is does is:什么是:

Create a “subclass” of the base Vue constructor.创建基本 Vue 构造函数的“子类”。 The argument should be an object containing component options.参数应该是一个包含组件选项的对象。

and one point to note here is:这里需要注意的一点是:

The special case to note here is the data option - it must be a function when used with Vue.extend().这里要注意的特殊情况是 data 选项 - 当与 Vue.extend() 一起使用时,它必须是一个函数。

You need to make changes similar to following in your code:您需要在代码中进行类似于以下的更改:

import MyComponent from './components/MyCompnent.vue';
const vmClass = Vue.extend(MyComponent)
const vm = new MyComponent();
vm.$mount('#some-place');

Try this尝试这个

Script :脚本 :

import MyComponent from './components/MyCompnent.vue';

export default {
    name : 'comp',
    components :{
      MyComponent
    }  
  }

Html You can call your component in html like this Html你可以像这样在 html 中调用你的组件

<template>
<mycomponent></mycomponent>
</template>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM