问题
The question may sound basic, but I am unable to figure out how to do it in VueJS
I have the following in html
<script>
var config = {'cols':4,'color':'red'}
</script>
<div id="app">
<mycomponent :config="config"></mycomponent>
</div>
var app = new Vue({
el: '#app',
data: {
// config: config // I do not want to pass this
}
})
Following is the use case:
- I know this isn't working because config variable in the component is looking for app.config
- I do not want to pass it as
data{ config:config }in the Vue Object. - I can pass it as
<mycomponent :config="{'cols':4,'color':'red'}"></mycomponent>but the config is going to be very long and this would be my last option. - And yes, this config does not change once the page loads, so I do not need to bind values.
Is there a way to do this?
回答1:
You can add a global member to Vue itself. Update: As Osuwariboy noted in the comments, for some reason Vue is not aware of itself by name in the un-minified version of Vue. It requires creating a Vue data item, which I have done below.
var app = new Vue({
el: '#app',
data: {
Vue
},
components: {
myComponent: {
template: '<div>{{config}}</div>',
props: ['config']
}
}
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.min.js"></script>
<script>
Vue.$config = {'cols':4,'color':'red'}
</script>
<div id="app">
<my-component :config="Vue.$config"></my-component>
</div>
来源:https://stackoverflow.com/questions/44267239/how-to-pass-a-javascript-object-to-component-in-vuejs