Vue.js  -  init a component inside a component programmatically

in javascript •  6 years ago  (edited)

Let’s say you have a component that is used on many pages within your app. Let’s say it’s modal window <modal-window> (dialog) that displays a form and the form is dynamically fetched (by AJAX) from your server. And let’s say the form contains a component  -  i.e. <awesome-icon>. How to tell the Vue there is a new component that should be set up? Well let’s see.

First of all you have to put the server response (the form HTML) into you modal window. You can do that by setting up a variable content and then “echo” the variable into the modal window. How to do that?

...
data() {
    formContent: null,
}
...

That will keep your form HTML. You can “echo” it into modal window like

...
<div v-html="formContent">
...

That gives rendered form but the component inside (the icon) won’t be compiled by Vue…

Just where you fetch the form from server initialize new Vue instance, set parent and that’s it. …

...
import AwesomeIcon from "./my_components/awesome_icon.vue"
new Vue({
    el: this.$el,
    components: {
        awesomeIcon: AwesomeIcon
    },
    parent: this
})
...

Done. Your component inside a component gets compiled. Remember technically you have <modal-window> -> Vue -> <awesome-icon>. So once you want to refer from inner component you have to do this.$parent.$parent.

You are welcome.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!