Search code examples
javascriptvue.jsundefinedpropdinamico

Vue props is undefined when print component dynamically


My problem is on the dynamically creation of the TAG "galeriaimages". Vue works fine but the props are always undefined

thanks for all.

main.js

import Vue from 'vue'
import Gi from './components/galeriaimages.vue'
import vuetify from './plugins/vuetify';

Vue.config.productionTip = false

document.addEventListener('DOMContentLoaded', function() {
    new Vue({vuetify, render: h => h(Gi) }).$mount('galeriaimages');
});

HTML

<galeriaimages p1="awesome" /> <!-- I create it dinamically-->

Vue component

<script>

export default {
    props: ['p1'] ,
    data: function() {
        return {
        }
    },
    created: function() {
        alert(this.p1); //this is always undefined
    }
}

Thanks to @skirtle for give me the answer :-)

I added this line in my vue.config.js

runtimeCompiler: true

...and all works fine


Solution

  • The bit where you write h(Gi) is creating a galeriaimages component but not passing any props to it.

    To pass the prop you would need to write:

    new Vue({
      vuetify,
      render: h => h(Gi, {props: {p1: 'awesome'}})
    }).$mount('galeriaimages');
    

    However, I suspect that isn't what you're really trying to do.

    You currently seem to be mounting directly to the <galeriaimages> element, which is a bit odd but if you remove the render function it should work. You can also use el instead of $mount:

    new Vue({
      vuetify,
      components: {galeriaimages: Gi},
      el: 'galeriaimages'
    });
    

    I would add that the reason most examples use a render function for the root Vue instance is that it avoids the need to include the template compiler in the Vue build. This only works if all your other Vue components are pre-built .vue files. If you have any templates at runtime, including those in your HTML, then you'll need to include the template compiler anyway. In that scenario there's no benefit to using a render function on the root instance.