1. 程式人生 > 程式設計 >vue 動態設定img的src地址無效,npm run build 後找不到檔案的解決

vue 動態設定img的src地址無效,npm run build 後找不到檔案的解決

動態設定img的src屬性無效,而直接寫可以

vue 動態設定img的src地址無效,npm run build 後找不到檔案的解決

解決辦法:

imgSrc寫成require('path');

vue 動態設定img的src地址無效,npm run build 後找不到檔案的解決

原因:

動態新增src被當做靜態資源處理了,沒有進行編譯

vue 動態設定img的src地址無效,npm run build 後找不到檔案的解決

npm run build 後出現 xxxxxxx net::ERR_FILE_NOT_FOUND

解決辦法:

進入:build資料夾 > 開啟 webpack.prod.conf.js

找到:output 物件

新增:publicPath:‘./'

具體寫法:

publicPath: process.env.NODE_ENV === 'production'
 ? './' +config.build.assetsPublicPath
 : './' + config.dev.assetsPublicPath

vue 動態設定img的src地址無效,npm run build 後找不到檔案的解決

補充知識:解決:vue專案npm run build 打包後 :src路徑裡面的本地圖片找不到

問題描述及錯誤程式碼:

// 本地執行、打包 圖片是ok的
<img src="../../static/images/orderSeeProgress0.png">   
 
// 本地執行 圖片是ok的、打包圖片找不到 (因為圖片的路徑被解析成了字串)
<img src="/static/images/orderSeeProgress1.png">  
 
// 本地執行 圖片是ok的、打包圖片找不到 (因為圖片的路徑被解析成了字串)
<img :src="'../../static/images/orderSeeProgress'+index+'.png'">  

解決辦法:

(1)如果使用的是靜態圖片,切路徑地址不會改變,那就直接使用 src 如下方法:(相對路徑的)

// 本地執行、打包 圖片是ok的

<img src="../../static/images/orderSeeProgress0.png">

(2)如果圖片是根據資料動態變化的,那麼就得使用 :src ( 動態改變src的值)

(2-1)首先在配置檔案裡面給static檔案起個別名:(我起得別名是@@)

build / webpack.base.conf.js 配置別名如下:

resolve: {
  extensions: ['.js','.vue','.json'],alias: {
   'vue$': 'vue/dist/vue.esm.js','@': resolve('src'),'@@': resolve('static'),}
 },

(2-2)引入圖片地址,然後在data裡面定義,在 :src裡面使用。

// 這樣使用: 本地、打包後 圖片都是ok的。
<img :src="orderPro1Img" />
<img :src="orderPro2Img" />
 
<script>
 import orderPro1 from '@@/images/orderSeeProgress0.png'
 import orderPro2 from '@@/images/orderSeeProgress1.png'
 export default {
  data() {
   return {
    msg: '',index:0,orderPro1Img:orderPro1,orderPro2Img:orderPro2
   }
  },}
</script>

以上這篇vue 動態設定img的src地址無效,npm run build 後找不到檔案的解決就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。