使用 vuejs 渲染函数中的额外类返回传递的插槽

Kus*_*our 3 vue.js vuejs2

我正在尝试创建一个组件,其任务是简单地在任何元素上添加一个类,当它只有一个节点时作为插槽传递给它

用法:

<my-component>
 <button>hello</button>
</my-component>
Run Code Online (Sandbox Code Playgroud)

输出:

<button class="added-by-component">hello</button>
Run Code Online (Sandbox Code Playgroud)

我尝试使用<template>标签,但<slot>不允许在根上。

即使使用render()函数,我也尝试在修改class属性后返回传递的插槽的 vnode :

render (createElement) {
 var vnode = this.$slots.default[0]
 vnode.data = vnode.data || {}
 vnode.data.class = { 'added-by-component': this.someCondition }
 return vnode
}
Run Code Online (Sandbox Code Playgroud)

即使这也不能按预期工作。即使条件为真,我也不会添加课程。

小智 5

const Wrapper = {
  functional: true,
  render (h, ctx) {
    const slots = ctx.slots()
    const node = slots.default[0]

    node.data.staticClass = [
      'my-class',
      node.data.staticClass || ''
    ].join(' ')

    return node
  }
}
Run Code Online (Sandbox Code Playgroud)

您也可以使用,data.class但它需要额外的类型处理。