Vue.js - 动态组件和事件

标签 vue.js vuejs2

我想知道如何处理 dynamic componentsevents使用 vue-js 2.3 .

假设组件 home $emit('eventFromHome')和组件 archives $emit('eventFromArchives')

<component></component> 中捕获它们的方法是什么? ?是否存在比临时解决方案更好/更好的方法?

动态组件

var vm = new Vue({
  el: '#example',
  data: {
    currentView: 'home'
  },
  components: {
    home: { /* ... */ },
    posts: { /* ... */ },
    archive: { /* ... */ }
  }
})

<component v-bind:is="currentView"></component>

静态组件

var vm = new Vue({
  el: '#example',
  data: {
    currentView: 'home'
  },
  components: {
    home: { /* ... */ },
    posts: { /* ... */ },
    archive: { /* ... */ }
  }
})

<home v-on:eventFromHome=""></home>
<archive v-on:eventFromArchive=""></archive>

临时回答

<component 
    v-bind:is="currentView"
    v-on:eventFromHome=""
    v-on:eventFromArchive="">
</component>

最佳答案

从 Vue.js 2.4 开始,v-on has an object syntax允许动态事件绑定(bind)。

这样,解决方案就更加优雅了:

var vm = new Vue({
  el: '#example',
  data: {
    currentView: {
      component: 'home',
      events: {}, // <-- put listeners here
    }
  },
  components: {
    home: { /* ... */ },
    posts: { /* ... */ },
    archive: { /* ... */ }
  }
})

<component v-bind:is="currentView.component" v-on="currentView.events"></component>

关于Vue.js - 动态组件和事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44316309/

相关文章:

vue.js - 如何使用 Vue.js 和 Vuelidate 验证模糊字段

javascript - 点击事件带来单个用户的问题

javascript - 使用 v-on 指令或 watch 方法来检测表单字段中的更改是否更好?

javascript - 在 VueJS 中使用 Axios - 这个未定义

vuejs2 - Vue-Router: TypeError: this._router.init 不是函数

javascript - Express.js net::ERR_CONNECTION_CLOSED

javascript - Nuxt.JS 没有按我的需要渲染 block

javascript - 除了第一个测试之外,在所有测试中触发触发器后,Test-utils 不会更新 DOM

javascript - 渲染 v-for 列表错误顺序(新添加的项目在前)Vue.js

vue.js 注册 webcomponent