vue 自定义指令修改after 背景图片
维护老项目 我的需求是根据不同地区在after上加载不同地图
// 新建自定义指令 和data同级
directives: {after: {inserted(el, binding) {}}
}
// 使用自定义指令
<div v-after="cityName" class="city-other"></div>
// 自定义指令内容
const list = {酒泉市: 'jq',嘉峪关市: 'jyg',武威市: 'ww',兰州市: 'lz',张掖市: 'zy',金昌市: 'jc',临夏回族自治州: 'lxhz',定西市: 'dx',庆阳市: 'qy',白银市: 'by',天水市: 'ts',陇南市: 'ln',甘南藏族自治州: 'gnzz',平凉市: 'pl'
};
const style = document.createElement('style');
style.type = 'text/css';
// 定义伪元素的样式
const afterStyles = `.city-other::after {position: absolute;z-index: 1;content: '';top: 87px;right: 100px;width: 828px;height: 730px;background: url(${require('../../assets/home/map/' +list[binding.value] +'.png')}) no-repeat center;background-size: contain;}
`;
// 将样式添加到 <style> 元素中
if (style.styleSheet) {// 针对 IE 浏览器style.styleSheet.cssText = afterStyles;
} else {style.appendChild(document.createTextNode(afterStyles));
}
// 将 <style> 元素添加到文档的 <head> 中
document.head.appendChild(style);