简体   繁体   中英

How to pass a javascript object to component in VueJS?

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?

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM