Home.vue
<div v-color style="width: 100px; height: 100px"></div>
//v-color="要传的值"
main.js
// 随机颜色
Vue.directive("color", {
inserted(el, binding, vnode) {
console.log(el); //当前dom
console.log(binding); //标签属性
console.log(vnode);
el.style.backgroundColor = "#" + Math.floor(Math.random() * 16777216).toString(16)
},
update(el, binding, vnode) {
el.style.backgroundColor = "#" + Math.floor(Math.random() * 16777216).toString(16)
}
})
或(rgba)
// let r = Math.floor(Math.random() * 255);
// let g = Math.floor(Math.random() * 255);
// let b = Math.floor(Math.random() * 255);
// this.color = "#" + color;
或 (十六进制)
getRandomColor: function () {
const rgb = []
for (let i = 0; i < 3; ++i) {
let color = Math.floor(Math.random() * 256).toString(16)
color = color.length == 1 ? '0' + color : color
rgb.push(color)
}
return '#' + rgb.join('')
}
Vue2自定义指令随机颜色
于 2022-03-03 15:34:22 首次发布