我有一个动态视图:
<div id="myview">
<div :is="currentComponent"></div>
</div>
带有关联的 Vue 实例:
new Vue ({
data: function () {
return {
currentComponent: 'myComponent',
}
},
}).$mount('#myview');
这允许我动态更改我的组件。
就我而言,我有三个不同的组件:myComponent
、myComponent1
和 myComponent2
。我像这样在它们之间切换:
Vue.component('myComponent', {
template: "<button @click=\"$parent.currentComponent = 'myComponent1'\"></button>"
}
现在,我想将道具传递给 myComponent1
。
当我将组件类型更改为 myComponent1
时,如何传递这些道具?
propName="propValue"
上的属性传递道具。那是你的问题吗?
<myComponent1 propName="propValue">
我用 $parent.currentComponent = componentName
以编程方式更改组件
<div :is="currentComponent"></div>
。那就是你要添加属性的地方。
myComponent1
接受 props,而 myComponent2
不接受 props
要动态传递道具,您可以将 v-bind
指令添加到动态组件并传递包含道具名称和值的对象:
所以你的动态组件看起来像这样:
<component :is="currentComponent" v-bind="currentProperties"></component>
在您的 Vue 实例中,currentProperties
可以根据当前组件进行更改:
data: function () {
return {
currentComponent: 'myComponent',
}
},
computed: {
currentProperties: function() {
if (this.currentComponent === 'myComponent') {
return { foo: 'bar' }
}
}
}
所以现在,当 currentComponent
为 myComponent
时,它将具有等于 'bar'
的 foo
属性。如果不是,则不会传递任何属性。
您也可以不使用计算属性并内联对象。
<div v-bind="{ id: someProp, 'other-attr': otherProp }"></div>
显示在 V-Bind 的文档中 - https://v2.vuejs.org/v2/api/#v-bind
你可以像这样构建它...
comp: { component: 'ComponentName', props: { square: true, outline: true, dense: true }, model: 'form.bar' }
我有同样的挑战,由以下解决:
<component :is="currentComponent" v-bind="resetProps">
{{ title }}
</component>
脚本是
export default {
…
props:['title'],
data() {
return {
currentComponent: 'component-name',
}
},
computed: {
resetProps() {
return { ...this.$attrs };
},
}
<div
:color="'error'"
:onClick="handleOnclick"
:title="'Title'"
/>
我来自 reactjs,我发现这解决了我的问题
如果您通过 require 导入了代码
var patientDetailsEdit = require('../patient-profile/patient-profile-personal-details-edit')
数据:函数(){返回{当前视图:患者详细信息编辑,}
如果您的组件已分配它,您还可以通过 name 属性引用组件
currentProperties: function() { if (this.currentView.name === 'Personal-Details-Edit') { return { mode: 'create' } } }
不定期副业成功案例分享
<slot>
。 vuejs.org/v2/guide/components-slots.html