问题
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?
回答1:
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"/>'
})
回答2:
The template in App.vue is simple like this:
<template>
<div id="app" source="mySource">
<router-view/>
</div>
</template>
回答3:
If I understand you properly, this sounds like a bad idea. Props are for creating a reactive pipe to dynamic data, to update the dom. Links to scripts and stylesheets are not like other dom content, and loading css dynamically requires special treatment. You can't just change the href on the fly.
Why do you want to do this? There has to be a cleaner way.
来源:https://stackoverflow.com/questions/50756855/init-app-component-with-props-using-vuejs