Vue+tsx使用slot沒有被替換的問題

前言

最近自己準備寫一個 UI 組件,想對 vue2.x3.x 可以更深層次的掌握

在架構時,準備全部使用 tsx 書寫組件

但遇到瞭 tsx 中使用 slot 的問題

發現問題

先寫瞭一個基礎的 card 組件:

card.tsx:

import Component from 'vue-class-component'
import VanUIComponent from '@packs/common/VanUIComponent'
import { VNode } from 'vue'
import { Prop } from 'vue-property-decorator'
import { CardShadowEnum } from '@packs/config/card'

@Component
export default class Card extends VanUIComponent {
  @Prop({
    type: String,
    default: undefined
  }) public headerPadding !: string | undefined

  @Prop({
    type: String,
    default: ''
  }) public title !: string

  @Prop({
    type: String,
    default: CardShadowEnum.Hover
  }) public shadow !: CardShadowEnum

  public static componentName = 'v-card'

  public get wrapperClassName(): string {
    const list: string[] = ['v-card__wrapper']

    list.push(`shadow-${ this.shadow }`)

    return list.join(' ')
  }

  public render(): VNode {
    return (
      <div class={ this.wrapperClassName }>
        <div class="v-card__header" style={ { padding: this.headerPadding } }>
          {
            this.$slots.title ? <slot name="title" /> : <div>{ this.title }</div>
          }
        </div>
        <div class="v-card__body">
          <slot name="default" />
        </div>
        <div class="v-card__footer"></div>
      </div>
    )
  }
}

examples 中使用這個 v-card 的時候:

<template>
  <v-card>
    <template #title>1111</template>
  </v-card>
</template>

<script lang="ts">
import Vue from 'vue'
import Component from 'vue-class-component'

@Component
export default class Components extends Vue {

}
</script>

<style lang="scss" scoped>
.components__wrapper {
  padding: 20px;
}
</style>

我發現渲染後,瀏覽器不替換 slot 標簽:

沒有替換slot標簽

我在百度、Google尋找瞭一天也沒有解釋,在官方文檔中仔仔細細閱讀後,也沒有類似的提示,以及 jsx 編譯器的文檔中也沒有寫明,隻是聲明瞭如何使用命名 slot

解決

第二天,我一直在糾結這個,也查瞭 element-uiant-design-vueUI 組件庫中如何書寫,也沒有找到對應的使用 jsx 使用 slot 的。

不甘放棄的我更換瞭搜索文字,於是終於找到解決方案,並將代碼改為:

...
  public render(): VNode {
    return (
      <div class={ this.wrapperClassName }>
        <div class="v-card__header" style={ { padding: this.headerPadding } }>
          {
            this.$slots.title ?? <div>{ this.title }</div>
          }
        </div>
        <div class="v-card__body">
          <slot name="default" />
        </div>
        <div class="v-card__footer"></div>
      </div>
    )
  }
...

再查看瀏覽器渲染:

在這裡插入圖片描述

問題解決

後記

在使用 jsx / tsx 時,如果 js 語法本身可以解決的,或本身註冊在 this 上的方法,優先使用 js 去做,例如 v-if / v-else 可以使用 雙目運算符 替代。實在沒有可用的簡便方法,再使用 vue 的指令做,例如 v-show

到此這篇關於Vue+tsx使用slot沒有被替換的問題的文章就介紹到這瞭,更多相關Vue+tsx slot沒有被替換內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: