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