我有一个动态视图:

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

现在,我想把props 传给myComponent1.

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

推荐答案

要动态传递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' }
    }
  }
}   

现在,当currentComponentmyComponent时,它的foo属性等于'bar'.否则,不会传递任何属性.

Vue.js相关问答推荐

如何使用composition api v-model Select 框获取其他JSON 值?

Vuejs 通过数据键迭代复杂对象

在 VueJS 中为 Get、Post、Patch 配置全局标头的最佳方法

Webpack 导入的模块不是函数

使用数组元素的计算(computed)属性

如何在 vue.js 2 的其他组件中调用方法?

Laravel Vue - 如何让 vue 在公共文件夹中查找图像

Polyfill for ie

Nuxt & Vuetify:如何控制 CSS 文件的加载顺序?

将自定义部分添加到 v-autocomplete 下拉列表

SVG 加载 vue-svg-loader; [Vue 警告]:无效的组件定义

全局禁用 vuetify 组件的涟漪效应

命名空间模块身份验证的重复命名空间身份验证

如何禁用 nuxt 默认错误重定向

触发子函数

Vuetify v-btn 路由活动类问题

使用 puppeteer 生成 PDF 而不保存

脚本npm run dev和npm run watch是做什么用的?

如何在 Vue.js 中延迟 @keyup 处理程序

使用 VueJS 使用 3rd 方库打印元素