vue中使用require动态拼接img路径
一般情况下,我们在使用require存放一个图片地址时,都是这么写:
<img width="100%; height: 100%" :src="bannarsrc" /> <script> data () { return { bannarsrc: require('@/assets/images/bannar-small.png') } } </script>
然后当适配不同的设备时直接对这个地址进行赋值即可
changeBannarImage() { const phone = 414; //手机 const ipad = 768; //ipad //const ipadpro = 1024 //ipadpro if (document.body.clientWidth <= phone) { this.bannarsrc = require("@/assets/images/bannar-small.png"); } else if ( document.body.clientWidth >= phone && document.body.clientWidth <= ipad ) { this.bannarsrc = require("@/assets/images/bannar.png"); } else { this.bannarsrc = require("@/assets/images/bannar-big.png"); } }
mounted() { this.changeBannarImage(); window.onresize = () => { this.changeBannarImage(); }; }
但是当一次性要替换的图片过多时,比如给菜单这种很多图片进行赋值,那显然一个个的去写赋值肯定不行,于是可以使用for循环去赋值,但是由于require不能对变量进行赋值,于是要使用拼接的方式,这里我创建一个中间变量用来表示图片名称。
data结构如下
<script> export default { data() { return { menuList: [ { menuName: "公司章程", messageCount: "", menuMethod: "articles", src: "", }, { menuName: "消息通知", messageCount: 13, menuMethod: "message", src: "", }, { menuName: "待办中心", messageCount: 9, menuMethod: "dealt", src: "" }, { menuName: "新闻中心", messageCount: "", menuMethod: "news", src: "" }, { menuName: "知识平台", messageCount: "", menuMethod: "knowledge", src: "", }, { menuName: "计划任务", messageCount: 9, menuMethod: "plan", src: "" }, { menuName: "排班", messageCount: "", menuMethod: "scheduling", src: "", }, { menuName: "申请", messageCount: "", menuMethod: "apply", src: "" }, { menuName: "考勤&行政", messageCount: "", menuMethod: "attendance", src: "", }, ], menuSrc: [ "article{0}.png", "message{0}.png", "todo{0}.png", "new{0}.png", "know{0}.png", "plan{0}.png", "scheduling{0}.png", "apply{0}.png", "attendance{0}.png", ], }; }, }; </script>
适配时代码如下
changeMenuImage() { const menu_list = this.menuList; const phone = 414; //手机 const ipad = 768; //ipad //const ipadpro = 1024 //ipadpro let zoom = ""; if (document.body.clientWidth <= phone) { zoom = "1x"; } else if ( document.body.clientWidth > phone && document.body.clientWidth <= ipad ) { zoom = "2x"; } else { zoom = "3x"; } for (let index = 0; index < menu_list.length; index++) { const element = menu_list[index]; const src = this.menuSrc[index].replace("{0}", zoom); element.src = require(`@/assets/images/${src}`); } },
这样就避免一个个的赋值,即使再多一套图片也只需要多增加一个zoom的值就行