Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mount a vue component?

Tags:

vue.js

vuejs2

I normally import my components like so:

Vue.component('comments', require('./components/Comments.vue'));

But I wish to manually mount the .vue file depending on a condition. The docs state:

var MyComponent = Vue.extend({
    template: '<div>Hello!</div>'
})

var component = new MyComponent().$mount()
document.getElementById('app').appendChild(component.$el)

But how do I mount a component in a separate vue file?

like image 765
panthro Avatar asked Sep 14 '25 23:09

panthro


1 Answers

Don't manually mount components, it's generally only useful in testing and certain circumstances where you can only mount after an element becomes available (i.e. when integrating with legacy code).

In the case of single file components, your base component is already mounted so Vue will handle this for you. In your case you should use v-if which only mounts the component when the condition is met; you don't have to do it manually.

Here's the JSFiddle: https://jsfiddle.net/5p3nq001/

like image 195
craig_h Avatar answered Sep 16 '25 13:09

craig_h