最近在寫一個后臺系統(tǒng)項目,有一個選擇功能是以圖片為背景的,就想提煉出一個組件公用;但在img動態(tài)綁定的時候出現(xiàn)了問題,在本地運行時img是正常顯示的,但build打包后就不行,img顯示不;
通過分析發(fā)現(xiàn)build后的img是通過靜態(tài)資源轉碼的,也就是在img的后面加上hash值,且是按需加載的,但HTML的img是動態(tài)生成的,所以在build的后的img是沒有hash值的;
原代碼如下:
HTML部分
<dd>
<div v-bind:class="[currentgame[0]['typegame'] == Active?'activeImg':'']" @click="addActive(currentgame[0]['typegame'])">
<img :img=" '../../../../static/images/'+currentgame[0]['typegame']+'png' " alt="">
<p>
<i class="fa fa-check-circle-o"></i>
</p>
</div>
<span>{{currentgame[0]['name']}}</span>
</dd>
js部分:
<script>
export default{
data(){
return{
Active:'',
activeContent:
[
[
{
"typegame": "cat",
"name": "小貓釣魚"
}
]
]
</script>
這時,本地運行時沒問題的,但build后報錯;
對代碼進行改進;
HTML部分:
<dd>
<div v-bind:class="[currentgame[0]['typegame'] == Active?'activeImg':'']" @click="addActive(currentgame[0]['typegame'])">
<img :img=" currentgame[0]['img']" alt="">
<p>
<i class="fa fa-check-circle-o"></i>
</p>
</div>
<span>{{currentgame[0]['name']}}</span>
</dd>
js部分,這時就需要用到 require引入文件
<script>
const cat = require('../../../../static/images/cat.png');
export default{
data(){
return{
Active:'',
activeContent:
[
[
{
"typegame": "cat",
"name": "小貓釣魚",
"img":cat
}
]
]
</script>
這時本地img將會加上hash值,img已經被引用,build后的img就是原來require時的;
主意此時的activeContent數(shù)據(jù)中增加了“img”對象,以便:img引用,如果用“typegame”則不會尋找img的url,僅僅會顯示“cat”;
以上代碼僅為示例部分代碼;