【问题标题】:Vue - Accessing slot children classes in render functionVue - 在渲染函数中访问插槽子类
【发布时间】:2021-09-12 21:18:57
【问题描述】:

我有一个具有默认插槽的组件,并且在渲染函数中,我试图将 slot 中的每个项目包装在一个 div 内,以便更好地控制布局。

我需要抓取其中一个插槽元素类(如果存在)以将其添加到包装器元素中,但 VNode 元素在函数运行时没有 elm$el 可用,它是还是undefined

父组件模板:

<Parent>
   <span>child 1</span>
   <p class="push">child 2</p>
   <Child>child 3</Child>
</Parent>

预期的渲染结果:

<Parent>
   <Wrapper>
      <span>child 1</span>
   </Wrapper>
   <Wrapper class="push">
      <p>child 2</p>
   </Wrapper>
   <Wrapper>
      <Child>child 3</Child>
   </Wrapper>
</Parent>

目前,这是我的渲染函数,它正确地包装了每个元素,但是它没有在 slot children 中找到类,它似乎无法访问!

render(createElement) {
    const childs = [];
    this.$slots.default.forEach(item => {
      if (item.tag) {
        console.log(item.elm, item.componentInstance); // both returns undefined
        childs.push(createElement("Wrapper", [item]));
      }
    });

    return createElement(this.tag, { class: this.classes }, childs);
  }

那么,如何在渲染函数中访问 slot 元素的类?

【问题讨论】:

    标签: javascript vue.js jsx


    【解决方案1】:

    您可以使用data.staticClass 属性:

    Vue.component("Child", {
      template: `
        <div>
          <slot />
        </div>
      `
    })
    Vue.component("Wrapper", {
      template: `
      <div>
        <slot />
      </div>
      `
    })
    Vue.component("Parent", {
      data() {
        return {
          tag: 'div'
        }
      },
      render(createElement) {
        const children = [];
        this.$slots.default.forEach(item => {
          if (item.tag) {
            let wrapperClasses = null
            if (item?.data?.staticClass) {
              // extracting the static class
              wrapperClasses = item.data.staticClass
    
              // "null"ing the static class on the passed in item
              item.data.staticClass = null
            }
            children.push(createElement(
              "Wrapper", {
                class: wrapperClasses
              }, [item]
            ));
          }
        });
        return createElement(this.tag, children);
      }
    })
    new Vue({
      el: "#app",
      template: `
        <div>
          <Parent>
            <span class="pull">child 1</span>
            <p class="push">child 2</p>
            <Child>child 3</Child>
          </Parent>
        </div>
      `
    })
    .push {
      color: red;
    }
    
    .pull {
      color: green;
    }
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
    <div id="app"></div>
    • 您可以在控制台中查看类。

    【讨论】:

      猜你喜欢
      • 2017-02-27
      • 2022-10-06
      • 2021-02-01
      • 2018-12-06
      • 2021-04-16
      • 2019-02-20
      • 2021-05-28
      • 2019-03-07
      • 2020-06-03
      相关资源
      最近更新 更多