整体环境
- Vue3 + TypeScript
- Ant Design Vue 2.x
代码
props中的value
和length
不用在setup函数中return,可以直接在template
中使用
<template>
<a-tooltip v-if="showTooltip">
<template v-slot:title> {{ value }}</template>
{{ ellipsis(value) }}
</a-tooltip>
<span v-else>{{ value }}</span>
</template>
<script lang="ts">
import { computed } from "vue";
/**
* 字符串截取组件
*/
export default {
name: "SuEllipsis",
props: {
// 内容
value: {
type: String,
required: true,
},
// 保留长度
length: {
type: Number,
default: 25,
},
},
setup(props) {
// 是否显示tooltip
const showTooltip = computed(() => props.value.length > props.length);
/**
* @description: 截取字符串
* @param {string} value 要截取的字符串
* @return {string} 截取后的字符串
*/
function ellipsis(value: string) {
if (!value) {
return "";
}
if (value.length > props.length) {
return value.slice(0, props.length) + "...";
}
return value;
}
return {
ellipsis,
showTooltip,
};
},
};
</script>
<style lang="scss">
</style>