Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Init app component with props using VueJs

I use VueJs with VueCli, and I would like to load a CSS file according to a "source" parameter that would be passed to the initiation of my main App component.

I would like to initialize my component like this in the index file: Main.js:

import Vue from 'vue'
import App from './App'
import router from './router'
import VueLadda from 'vue-ladda'
import VueResource from 'vue-resource'
import VModal from 'vue-js-modal'
import BootstrapVue from 'bootstrap-vue'

Vue.use(VModal);
Vue.use(BootstrapVue);

Vue.use(VueResource);
Vue.config.productionTip = false
Vue.component('vue-ladda', VueLadda)

new Vue({
  el: '#app',
  props: ['source'],
  router,
  render: h => h(App)
})

Here my App component (App.vue)

<script>
export default {
  name: 'App',
  props: ['source'],
  data: function () {
    return {
    }
  },
  mounted: function () {
    console.log(this.source)
  }
}
</script>

But I get undifined. Someone would have an idea why?

like image 965
Jonathan COHEN Avatar asked Jul 04 '26 02:07

Jonathan COHEN


1 Answers

You are not passing props on the root component, you are registering a prop name source.

You can pass props in the render function's createElement alias h function itself

new Vue({
  el: '#app',
  props: ['source'],
  router,
  render: h => h(App, {props:{ source:' source prop'}})
})

Or you can replace the render option with a template option to pass props to App.vue

new Vue({
  el: '#app',
  props: ['source'],
  router,
  components:{App},
  template: '<App source="source prop"/>'
})
like image 132
Vamsi Krishna Avatar answered Jul 06 '26 16:07

Vamsi Krishna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!