vue3 全局定义动态样式
1. 自定义需要的样式js文件
// 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'}
}2. main.js注册
import stateColor from '~/composables/stateColor' // 引用const app = createApp(App);
(async () => {app.directive('state-color', stateColor);app.mount('#app');
})();3.在vue文件中运用
<template><div v-state-color="item.PRO_STATE_CD"> 哈哈哈 </div>
</template>4.效果:

