将道具动态传递给VueJS中的动态组件

新手上路,请多包涵

我有一个动态视图:

 <div id="myview">
  <div :is="currentComponent"></div>
</div>

带有关联的 Vue 实例:

 new Vue ({
  data: function () {
    return {
      currentComponent: 'myComponent',
    }
  },
}).$mount('#myview');

这允许我动态更改我的组件。

就我而言,我有三个不同的组件: myComponentmyComponent1myComponent2 。我像这样在它们之间切换:

 Vue.component('myComponent', {
  template: "<button @click=\"$parent.currentComponent = 'myComponent1'\"></button>"
}

现在,我想将道具传递给 myComponent1

当我将组件类型更改为 myComponent1 时,如何传递这些道具?

原文由 Epitouille 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 358
2 个回答

要动态传递道具,您可以将 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' }
    }
  }
}

所以现在,当 currentComponentmyComponent 时,它将有一个 foo 属性等于 'bar' 。如果不是,则不会传递任何属性。

原文由 thanksd 发布,翻译遵循 CC BY-SA 3.0 许可协议

您也可以不使用计算属性并内联对象。

<div v-bind="{ id: someProp, 'other-attr': otherProp }"></div>

显示在 V-Bind 的文档中 - https://v2.vuejs.org/v2/api/#v-bind

原文由 Jquestions 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题