4th Street Bar Hive-Bar

Hive-Bar Powered by Hive beta-fdb5b5b

Community post

Vue.js  -  init a component inside a component programmatically

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.parent.

You are welcome.

1 upvotes $0.00

Replies (0)

Conversation

No replies yet

Replies will appear here as people join the conversation.

Review before signing

Posting as . Signing with . Keychain permission: Posting. Hive Keychain will ask you to approve this action next.


  
Technical details

Operation fingerprint: