本篇内容介绍了“Vue+tsx使用slot没有被替换的问题怎么解决”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
前言
发现问题
解决
后记
最近自己准备写一个 UI
组件,想对 vue
的 2.x
、3.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
标签:
我在百度、Google寻找了一天也没有解释,在官方文档中仔仔细细阅读后,也没有类似的提示,以及 jsx
编译器的文档中也没有写明,只是声明了如何使用命名 slot
。
第二天,我一直在纠结这个,也查了 element-ui
、ant-design-vue
的 UI
组件库中如何书写,也没有找到对应的使用 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没有被替换的问题怎么解决”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。