javascript - 将 Prop 动态传递给 VueJS 中的动态组件

标签 javascript vue.js vuejs2 vue-component

我有一个动态 View :

<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 指令添加到您的动态组件并传递一个包含您的 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'。如果不是,则不会传递任何属性。

关于javascript - 将 Prop 动态传递给 VueJS 中的动态组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43658481/

相关文章:

javascript - 启动 Meteor 时为 "ReferenceError: Plugin is not defined"

javascript - 在数组中查找字符串

php - Laravel Echo 不听

php - 如何在同一本地主机的现有 vue 应用程序中集成并运行 php?

javascript - 如何限制Vue中的分页按钮?

javascript - jQuery : extract tag from data

vue.js - 从相同的axios到不同的组件,VueJS

javascript - 由于 HTML 内容限制,标签 <slot> 不能出现在 <table> 内。它将被浏览器从 <table> 中提升出来

vue.js - 有没有办法在两个命名空间的 vuex 模块之间分派(dispatch)操作?

javascript - Chrome 在窗口聚焦(即打开)时读取内容