vue3 全局定义动态样式

  1. 自定义需要的样式js文件
javascript 复制代码
// stateColor.js
export default {
    mounted(el, binding) {
        setStyle(el, binding.value)
    },
    updated(el, binding) {
        setStyle(el, binding.value)
    }
}

function setStyle(el, stateCd) {
    const cd = Number(stateCd)

    if ([4, 7].includes(cd)) {
        el.style.color = 'red'
        el.style.fontWeight = 'bold'
        // 可扩展其它样式
        // el.style.fontSize = '14px'
        // el.style.textDecoration = 'underline'
    } else if (cd == 3) {
        el.style.color = 'blue'
        el.style.fontWeight = 'normal'
    } else {
        el.style.color = 'gray'
        el.style.fontWeight = 'normal'
    }
}
  1. main.js注册
javascript 复制代码
import stateColor from '~/composables/stateColor' // 引用
 

const app = createApp(App);
(async () => {

    app.directive('state-color', stateColor);

    app.mount('#app');
})();

3.在vue文件中运用

javascript 复制代码
<template>
    <div v-state-color="item.PRO_STATE_CD"> 哈哈哈 </div>
</template>

4.效果:

相关推荐
kyriewen117 小时前
你点的“刷新”是假刷新?前端路由的瞒天过海术
开发语言·前端·javascript·ecmascript·html5
摇滚侠8 小时前
JAVA 项目教程《苍穹外卖-12》,微信小程序项目,前后端分离,从开发到部署
java·开发语言·vue.js·node.js
Timer@9 小时前
LangChain 教程 04|Agent 详解:让 AI 学会“自己干活“
javascript·人工智能·langchain
阿珊和她的猫9 小时前
TypeScript中的never类型: 深入理解never类型的使用场景和特点
javascript·typescript·状态模式
skywalk81639 小时前
Kotti Next的tinyfrontend前端模仿Kotti 首页布局还是不太好看,感觉比Kotti差一点
前端
RopenYuan11 小时前
FastAPI -API Router的应用
前端·网络·python
走粥11 小时前
clsx和twMerge解决CSS类名冲突问题
前端·css
Purgatory00112 小时前
layui select重新渲染
前端·layui
weixin1997010801612 小时前
《中国供应商商品详情页前端性能优化实战》
前端·性能优化