How to pass a javascript object to component in VueJS?

£可爱£侵袭症+ 提交于 2019-12-21 17:44:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!