Vue.js  -  init a component inside a component programmatically

in #javascript4 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.

Coin Marketplace

STEEM 0.25
TRX 0.07
JST 0.031
BTC 22893.68
ETH 1672.16
USDT 1.00
SBD 3.16