1. 程式人生 > 其它 >Vue中:src獲取後臺傳回本地資源路徑失效問題

Vue中:src獲取後臺傳回本地資源路徑失效問題

技術標籤:筆記vue

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