简体   繁体   English

如何将javascript对象传递给VueJS中的组件?

[英]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 这个问题可能听起来很基本,但我无法弄清楚如何在VueJS中做到这一点

I have the following in html 我在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 我知道这不起作用,因为组件中的配置变量正在寻找app.config
  • I do not want to pass it as data{ config:config } in the Vue Object. 我不想将它作为data{ config:config }传递给Vue对象。
  • 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. 我可以将其作为<mycomponent :config="{'cols':4,'color':'red'}"></mycomponent>但配置将会非常长,这将是我的最后一个选项。
  • 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. 您可以将全局成员添加到Vue本身。 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. 更新:正如Osuwariboy在评论中指出的那样,出于某种原因,Vue在Vue的未缩小版本中没有注意到自己的名字。 It requires creating a Vue data item, which I have done below. 它需要创建一个Vue数据项,我在下面做了。

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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