Vue.js中NaiveUI組件文字漸變的實現(xiàn)
前言
NaiveUI中有著一個非常有意思的組件,就是漸變文字組件,如下圖:

有意思的點是這段文字描述這個東西看起來沒啥用,實際上確實沒啥用。
這里我們用Vue3.2+TS來實現(xiàn)這個簡單的小組件。
漸變文字
漸變文字的實現(xiàn)比較簡單,利用background-clip屬性就可以實現(xiàn),該屬性存在一個text屬性值,它可以將背景作為文字的前景色,配合漸變就可以實現(xiàn)漸變文字了,
示例代碼如下:
<span class="ywz-gradient-text">漸變文字</span>
.ywz-gradient-text {
display: inline-block;
font-weight: 700;
font-size: 32px;
background-clip: text;
-webkit-background-clip: text;
color: transparent;
white-space: nowrap;
background-image: linear-gradient(
252deg,
rgba(24, 160, 88, 0.6) 0%,
#18a058 100%
);
}代碼運行效果如下:

封裝漸變組件
我們現(xiàn)在開始使用Vue3+TS來封裝這個漸變組件,其實非常簡單,就是通過自定義屬性和動態(tài)class實現(xiàn)不同的文字漸變效果。
定義props
這里我們定義4個props,也就是漸變文字具有4個屬性,分別如下:
type:預設的漸變效果size:漸變文字的大小weight:漸變文字的粗細gradient:可以自定義漸變顏色
實現(xiàn)代碼如下:
type TextType = 'error' | 'info' | 'warning' | 'success'
type WeightType = 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | 'normal' | 'bold'
type RotateType = 'to left' | 'to right' | 'to bottom' | 'to top' | number
interface IGradient {
rotate: RotateType // 線性漸變方向
start: string // 開始的色值
end: string // 結(jié)束的色值
}
interface Props {
type?: TextType
size?: string
gradient?: IGradient
weight?: WeightType
}
const props = defineProps<Props>()上面就是我們這個組件中唯一的TS代碼,只有這些了,因為這個組件中沒有任何的邏輯部分。
實現(xiàn)組件效果
首先我們先將預設的那四個漸變效果的CSS進行定義一下,示例代碼如下:
.error { background-image: linear-gradient( 252deg, rgba(208, 48, 80, 0.6) 0%, #d03050 100% );}
.info { background-image: linear-gradient( 252deg, rgba(32, 128, 240, 0.6) 0%, #2080f0 100%);}
.warning { background-image: linear-gradient( 252deg, rgba(240, 160, 32, 0.6) 0%, #f0a020 100% );}
.success { background-image: linear-gradient( 252deg, rgba(24, 160, 88, 0.6) 0%, #18a058 100% ); }現(xiàn)在我們來定義一下<template>中的內(nèi)容:
<template>
<span
class="ywz-gradient-text"
:class="[props.type, props.gradient ? 'custom-gradient' : '']"
:style="{
'--size': props.size ?? '16px',
'--weight': props.weight ?? '400',
'--rotate':
typeof props.gradient?.rotate === 'number'
? props.gradient?.rotate + 'deg'
: props.gradient?.rotate,
'--start': props.gradient?.start,
'--end': props.gradient?.end,
}"
>
<!-- 默認插槽,也就是文字 -->
<slot></slot>
</span>
</template>上面的代碼中通過動態(tài)class實現(xiàn)不同預設的展示以及自定義漸變的展示。
上面的代碼中存在??和?.這兩個運算符,這兩個是ES2020中增加的新特性,如果不了解可以通過下面這篇文章來了解一下ECMAScript中的所有新特性:
JavaScript ECMAScript 6(ES2015~ES2022)所有新特性總結(jié)
剩余的CSS代碼如下:
.ywz-gradient-text {
display: inline-block;
font-weight: var(--weight);
background-clip: text;
font-size: var(--size);
-webkit-background-clip: text;
color: transparent;
white-space: nowrap;
}
.custom-gradient {
background-image: linear-gradient(
var(--rotate),
var(--start) 0%,
var(--end) 100%
);
}到此這篇關(guān)于Vue.js中NaiveUI組件文字漸變的實現(xiàn)的文章就介紹到這了,更多相關(guān)Vue.js NaiveUI組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue?3.0使用element-plus按需導入方法以及報錯解決
Vue3是不能直接使用Element-ui了,需要換成Element-plus,下面這篇文章主要給大家介紹了關(guān)于vue?3.0使用element-plus按需導入方法以及報錯解決的相關(guān)資料,需要的朋友可以參考下2024-02-02

