vue 包装另一个组件,传递道具和事件

vue wrap another component, passing props and events

如何编写我的组件来包装另一个 vue 组件,同时我的包装器组件获得一些额外的道具?我的包装模板组件应该是:

<wrapper-component>
   <v-table></v-table> <!-- pass to v-table all the props beside prop1 and prop2 -->
</wrapper-component>

和包装道具:

props: {
  prop1: String,
  prop2: String
}

这里我想包装一个 table 组件,并将传递给包装器的所有道具和事件传递给 table 组件,除了两个额外的道具 prop1prop2。在 vue 中执行此操作的正确方法是什么? 事件也有解决方案吗?

将您希望包装的组件放入包装器组件的模板中,将 v-bind="$attrs" v-on="$listeners" 添加到该组件标签,然后将内部组件(以及可选的 inheritAttrs: false)添加到包装器组件的配置对象。

Vue 的文档似乎没有在指南或其他任何内容中涵盖这一点,但是 $attrs, $listeners, and inheritAttrs can be found in Vue's API documentation. Also, a term that may help you when searching for this topic in the future is "Higher-Order Component" (HOC) 的文档 - 这与您对 "wrapper component" 的使用基本相同。(这术语是我最初找到 $attrs)

的方式

例如...

<!-- WrapperComponent.vue -->
<template>
    <div class="wrapper-component">
        <v-table v-bind="$attrs" v-on="$listeners"></v-table>
    </div>
</template>

<script>
    import Table from './BaseTable'

    export default {
        components: { 'v-table': Table },
        inheritAttrs: false // optional
    }
</script>

编辑:或者,您可能想使用dynamic components via the is attribute,这样您就可以传入要包装的组件作为道具(更接近高阶组件idea) 而不是它总是相同的内部组件。例如:

<!-- WrapperComponent.vue -->
<template>
    <div class="wrapper-component">
        <component :is="wraps" v-bind="$attrs" v-on="$listeners"></component>
    </div>
</template>

<script>
    export default {
        inheritAttrs: false, // optional
        props: ['wraps']
    }
</script>

编辑 2:OP 的原始问题中我遗漏的部分是传递除了一两个之外的所有道具。这是通过在包装器上显式定义 prop 来处理的。引用 $attrs 的文档:

Contains parent-scope attribute bindings (except for class and style) that are not recognized (and extracted) as props

例如,example1 在下面的代码片段中被识别并提取为道具,因此它不会作为被传递的 $attrs 的一部分包含在内。

Vue.component('wrapper-component', { 
  template: `
    <div class="wrapper-component">
        <component :is="wraps" v-bind="$attrs" v-on="$listeners"></component>
    </div>
  `,
  // NOTE: "example1" is explicitly defined on wrapper, not passed down to nested component via $attrs
  props: ['wraps', 'example1']
})

Vue.component('posts', {
  template: `
    <div>
      <div>Posts component</div>
      <div v-text="example1"></div>
      <div v-text="example2"></div>
      <div v-text="example3"></div>
    </div>
  `,
  props: ['example1', 'example2', 'example3'],
})

new Vue({
  el: '#app',
  template: `
    <wrapper-component wraps="posts"
      example1="example1"
      example2="example2"
      example3="example3"
    ></wrapper-component>
  `,
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>