Vue中:src获取后台传回本地资源路径失效问题

Vue中:src获取后台传回本地资源路径失效问题

最近使用mockjs发现了一个问题,就是:src获取由mockjs模拟后台传回本地静态资源路径失效

直接使用本地静态资源正常显示
<img src="@/assets/img/bg.jpg" alt=""/>
:src获取后台传回本地资源路径失效
<img :src="img" alt="" v-if="img"/>
data(){
	return{
		img: "",
	}
},
mounted(){
	this.getInfo();
},
methods:{
	getInfo(){
		 this.$axios.get("http://localhost:8081/home").then((res) => {
		 	console.log(res.data.data.img); //bg.jpg
            this.img ="@/assets/img/" + res.data.data.img;
         });
	}
}
解决方法一
<img :src="require('@/assets/img/' + img)" alt="" v-if="img"/>
data(){
	return{
		img: "",
	}
},
mounted(){
	this.getInfo();
},
methods:{
	getInfo(){
		 this.$axios.get("http://localhost:8081/home").then((res) => {
		 	console.log(res.data.data.img); //bg.jpg
            this.img = res.data.data.img;
         });
	}
}
解决方法二
<img :src="getImg(img)" alt="" v-if="img"/>
data(){
	return{
		img: "",
	}
},
mounted(){
	this.getInfo();
},
methods:{
	getImg(url) {
      return require("@/assets/img/" + url);
    },
	getInfo(){
		 this.$axios.get("http://localhost:8081/home").then((res) => {
		 	console.log(res.data.data.img); //bg.jpg
            this.img = res.data.data.img;
         });
	}
}
解决方法三

将图片资源放到static目录下。

总结
  1. assets 在项目编译的过程中会被webpack处理解析为模块依赖,只支持相对路径的形式
  2. static目录下的文件不会被webpack处理,简单来说就是存放第三方文件的地方,不会被webpack解析。它会直接被复制到最终的打包目录(默认是dist/static)下,所以必须使用绝对路径引用这些文件
  3. 动态添加src被当做静态资源处理了,没有进行编译,所以要加上require
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值