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

19,484

Solution 1

Finally, I found the solution myself, very simple:

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

Solution 2

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. What is does is:

Create a “subclass” of the base Vue constructor. 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().

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

Solution 3

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

<template>
<mycomponent></mycomponent>
</template>
Share:
19,484
Alfred Huang
Author by

Alfred Huang

一切有为法, 如梦幻泡影。 如露亦如电, 应作如是观。

Updated on June 24, 2022

Comments

  • Alfred Huang
    Alfred Huang almost 2 years

    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:

    Uncaught TypeError: MyComponent.default is not a constructor

    So how if I want to create the component?

  • Alfred Huang
    Alfred Huang over 7 years
    I just want to initialize a vm instance, just like new Vue() returns.
  • Alfred Huang
    Alfred Huang over 7 years
    I just want to initialize a vm instance, just like new Vue() returns.
  • Artistan
    Artistan almost 7 years
    I believe that the component in html would be <my-component></my-component> because it is camel-cased.