如何将 javascript 对象传递给 VueJS 中的组件? [英] How to pass a javascript object to component in VueJS?
本文介绍了如何将 javascript 对象传递给 VueJS 中的组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这个问题可能听起来很基本,但我无法弄清楚如何在 VueJS 中做到这一点
我在html中有以下内容
<div id="应用程序"><mycomponent :config="config"></mycomponent>
var app = new Vue({el: '#app',数据: {//config: config//我不想传递这个}})
以下是用例:
- 我知道这不起作用,因为组件中的配置变量正在寻找 app.config
- 我不想在 Vue 对象中将它作为
data{ config:config }
传递. - 我可以将它作为
<mycomponent :config="{'cols':4,'color':'red'}"></mycomponent>
传递,但配置正在运行很长,这将是我最后的选择. - 是的,一旦页面加载,这个配置就不会改变,所以我不需要绑定值.
有没有办法做到这一点?
解决方案
您可以向 Vue 本身添加一个全局成员.更新: 正如 Osuwariboy 在评论中指出的那样,由于某种原因,Vue 在未缩小版本的 Vue 中不知道自己的名字.它需要创建一个 Vue 数据项,我已经在下面完成了.
var app = new Vue({el: '#app',数据: {视图},成分: {我的组件:{模板:'<div>{{config}}</div>',道具:['配置']}}});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.min.js"></script><脚本>Vue.$config = {'cols':4,'color':'red'}<div id="应用程序"><my-component :config="Vue.$config"></my-component>
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>
这篇关于如何将 javascript 对象传递给 VueJS 中的组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文