ChatGPT解决这个技术问题 Extra ChatGPT

将道具动态传递给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 时,如何传递这些道具?

您通过元素 propName="propValue" 上的属性传递道具。那是你的问题吗?
我不能,因为我从不写 <myComponent1 propName="propValue"> 我用 $parent.currentComponent = componentName 以编程方式更改组件
是的,但你写 <div :is="currentComponent"></div>。那就是你要添加属性的地方。
是的,但道具取决于组件。例如,myComponent1 接受 props,而 myComponent2 不接受 props
花了一个小时试图做到这一点。太感谢了!

t
thanksd

要动态传递道具,您可以将 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 时,它将具有等于 'bar'foo 属性。如果不是,则不会传递任何属性。


为什么这对我不起作用?它适用于第一个组件,但是在我更改“currentComponent”之后,我得到一个“e.currentProperties”在子组件上未定义。
@RicardoVigatti,没有看到你的任何代码,很难知道
@FelipeMorales,是的,您只需要为要动态呈现的每个组件定义一个默认 <slot>vuejs.org/v2/guide/components-slots.html
样式指南说道具名称应尽可能详细。这种方式打破了规则。这也是我使用的,但我正在寻找更好的解决方案。
@KorayKüpe 您在这里错误地引用了样式指南。它说“道具定义应始终尽可能详细”。动态组件的意图本质上意味着道具名称和结构在加载到此结构中的组件之间几乎肯定会有所不同。
t
tony19

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

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

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


K
Kornél Takó

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

comp: { component: 'ComponentName', props: { square: true, outline: true, dense: true }, model: 'form.bar' }


M
Montaser Almohasen

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

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


M
Mark Dowton

如果您通过 require 导入了代码

var patientDetailsEdit = require('../patient-profile/patient-profile-personal-details-edit')

数据:函数(){返回{当前视图:患者详细信息编辑,}

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

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


为什么使用函数?