将 props 动态传递给 VueJS 中的动态组件

IT技术 javascript vue.js vuejs2 vue-component
2021-02-14 04:26:08

我有一个动态视图:

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

带有关联的 Vue 实例:

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

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

就我而言,我有三个不同的部分组成:myComponentmyComponent1,和myComponent2我像这样在它们之间切换:

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

现在,我想将props传递给myComponent1.

当我将组件类型更改为 时,如何传递这些propsmyComponent1

5个回答

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

所以你的动态组件看起来像这样:

<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,它将具有foo等于属性'bar'如果不是,则不会传递任何属性。

@RicardoVigatti,没有看到您的任何代码,很难知道
2021-04-15 04:26:08
嘿,如果我想在<component>(here)</component>. 那可能吗?
2021-04-24 04:26:08
@FelipeMorales,是的,您只需要为<slot>动态渲染的每个组件定义一个默认值vuejs.org/v2/guide/components-slots.html
2021-04-27 04:26:08
风格指南说道具名称应该尽可能详细。这种方式打破了规则。这也是我使用的,但我正在寻找更好的解决方案。
2021-04-29 04:26:08
为什么这对我不起作用?它适用于第一个组件,但在我更改“currentComponent”后,我得到一个“e.currentProperties”在子组件上未定义。
2021-05-01 04:26:08

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

<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"/>

如果您已通过 require 导入您的代码

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

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

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

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

我有同样的挑战,由以下解决:

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