Vue.js 向Vue组件动态添加属性
我正在从数据库加载数据,该数据库驱动我显示的组件类型 AJAX调用将启动并返回一些数据(如果需要,可以重新构造) 这在我的父对象上是可访问的,一个名为组件的变量 在父对象的模板中,我有以下内容Vue.js 向Vue组件动态添加属性,vue.js,vuejs2,vue-component,Vue.js,Vuejs2,Vue Component,我正在从数据库加载数据,该数据库驱动我显示的组件类型 AJAX调用将启动并返回一些数据(如果需要,可以重新构造) 这在我的父对象上是可访问的,一个名为组件的变量 在父对象的模板中,我有以下内容 <component :is="component.component_type" ></component> 这可以正常工作,并按预期加载零部件 接下来,我还想将数据对象中的属性添加到此标记中 <component :is="component.component_t
<component :is="component.component_type" ></component>
这可以正常工作,并按预期加载零部件
接下来,我还想将数据对象中的属性添加到此标记中
<component :is="component.component_type" {{ component.props }} ></component>
这不起作用,拒绝写入包含{{的标记。我认为这是浏览器而不是Vue引发的错误,尽管我不确定
作为参考,我希望输出实际如下所示:
<component :is="component.component_type" name='test' value='some value' ></component>
我怎样才能传递这些属性呢?理想情况下,我希望这些属性与我正在展示的父级的数据/道具相关联,以便它们可以在数据库中轻松更改,UI也会相应地更改
最坏的情况下,我将在服务器端生成所有这些内容,但我更愿意像目前尝试的那样通过ajax来完成。据我所知,Vue.js模板中没有rest props(spread props)语法 一种可能的解决方案是渲染函数。在使用渲染函数时,您拥有JavaScript的全部功能,因此您可以执行以下操作:
render (h) {
return h('foo', {
props: {
...yourData
}
})
}
<div class="app">
<component is="component.component_type" v-props="component.props"></component>
</div>
我在这里创建了一个简单的示例:
组件类型(如foo
)和道具都可以是动态的(但您仍然需要在子组件中声明道具的所有可能字段(如a
、b
和c
)
还有另一个解决方案是JSX
使用JSX babel插件:
然后您可以使用spread props语法:
return <foo {...{yourData}}></foo>
返回
接下来,我看到了两个选项
一种方法是传递一个单独的道具,道具本身就是一个对象,并传递其中可由子组件使用的所有相关键值,如下所示:
<component :is="component. component_type"
:options="component.props"
</component>
然后像这样使用它:
render (h) {
return h('foo', {
props: {
...yourData
}
})
}
<div class="app">
<component is="component.component_type" v-props="component.props"></component>
</div>
如果有人想知道如何使用Vue 2执行此操作,您只需将一个对象传递给v-bind即可:
<template>
<component :is="componentType" v-bind="props"></component>
</template>
<script>
export default {
data() {
return {
componentType: 'my-component',
props: {
foo: 'foofoo',
bar: 'barbar'
}
}
}
}
</script>
导出默认值{
数据(){
返回{
componentType:“我的组件”,
道具:{
福:‘福福’,
酒吧:“芭芭拉”
}
}
}
}
我需要你的帮助。看看这个:我认为这也适用于Vue 1。我还没有测试过,但它在.Hmm中,我得到了app.js:211314[Vue warn]:指令props绑定钩子中的错误:“TypeError:尝试使用该指令时无法读取未定义的属性“vm”