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

Passing props dynamically to dynamic component in 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时如何传递这些道具?

要动态传递 props,您可以将 v-bind 指令添加到您的动态组件并传递一个包含您的 prop 名称和值的对象:

因此您的动态组件将如下所示:

<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'。如果不是,则不会传递任何属性。

如果您通过 require

导入了代码

var patientDetailsEdit = require('../patient-profile/patient-profile-personal-details-edit')
并初始化数据实例如下

data: function () {
            return {
                currentView: patientDetailsEdit,
            }

如果您的组件已分配,您还可以通过名称 属性 引用该组件

currentProperties: function() {
                if (this.currentView.name === 'Personal-Details-Edit') {
                    return { mode: 'create' }
                }
            }

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

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

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

你可以像这样构建它...

comp: { component: 'ComponentName', props: { square: true, outlined: true, dense: true }, model: 'form.bar' }
     
<component :is="comp.component" v-bind="{...comp.props}" v-model="comp.model"/>

我遇到了同样的挑战,解决方法如下:

<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,我发现这解决了我的问题