将频繁使用的 CSS 样式封装为了指令,可以不用写大量的 style 行内样式。以下是支持的指令:
v-display:设置元素的框类型 display
v-width:设置元素宽度 width
v-height:设置元素高度 height
v-margin:设置元素 margin 值
v-padding:设置元素 padding 值
v-font:设置元素 fontSize
v-color:设置元素 color
v-bg-color:设置元素 background-color
styles.js导出样式指令
// 样式指令
const styles = {
// 设置元素的框类型
display: {
inserted: (el, binding) => {
el.style.display = binding.value
},
update: (el, binding) => {
el.style.display = binding.value
}
},
// 设置元素宽度
width: {
inserted: (el, binding) => {
el.style.width = binding.value + 'px'
},
update: (el, binding) => {
el.style.width = binding.value + 'px'
}
},
// 设置元素高度
height: {
inserted: (el, binding) => {
el.style.height = binding.value + 'px'
},
update: (el, binding) => {
el.style.height = binding.value + 'px'
}
},
// 设置元素 margin 值
margin: {
inserted: (el, binding) => {
el.style.margin = binding.value + 'px'
},
update: (el, binding) => {
el.style.margin = binding.value + 'px'
}
},
// 设置元素 padding 值
padding: {
inserted: (el, binding) => {
el.style.padding = binding.value + 'px'
},
update: (el, binding) => {
el.style.padding = binding.value + 'px'
}
},
// 设置元素 fontSize
font: {
inserted: (el, binding) => {
el.style.fontSize = binding.value + 'px'
},
update: (el, binding) => {
el.style.fontSize = binding.value + 'px'
}
},
// 设置元素 color
color: {
inserted: (el, binding) => {
el.style.color = binding.value
},
update: (el, binding) => {
el.style.color = binding.value
}
},
// 设置元素 background-color
bgColor: {
inserted: (el, binding) => {
el.style.backgroundColor = binding.value
},
update: (el, binding) => {
el.style.backgroundColor = binding.value
}
}
}
export default styles
index.js导出注册全局指令
// 全局指令
import styles from './module/styles'
const vueDirective = Vue => {
// 样式指令
Object.keys(styles).forEach((key) => {
Vue.directive(key, styles[key])
})
}
export default vueDirective
main.js调用函数注册
import Vue from 'vue'
import vueDirective from './directive'
vueDirective(Vue)