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.效果:

相关推荐
子兮曰3 小时前
OpenClaw入门:从零开始搭建你的私有化AI助手
前端·架构·github
吴仰晖3 小时前
使用github copliot chat的源码学习之Chromium Compositor
前端
1024小神3 小时前
github发布pages的几种状态记录
前端
不像程序员的程序媛6 小时前
Nginx日志切分
服务器·前端·nginx
Daniel李华6 小时前
echarts使用案例
android·javascript·echarts
北原_春希6 小时前
如何在Vue3项目中引入并使用Echarts图表
前端·javascript·echarts
JY-HPS6 小时前
echarts天气折线图
javascript·vue.js·echarts
尽意啊6 小时前
echarts树图动态添加子节点
前端·javascript·echarts
吃面必吃蒜6 小时前
echarts 极坐标柱状图 如何定义柱子颜色
前端·javascript·echarts
O_oStayPositive6 小时前
Vue3使用ECharts
前端·javascript·echarts