1. 程式人生 > >Vue中img的src動態賦值本地路徑報錯

Vue中img的src動態賦值本地路徑報錯

問題:我想根據tabIndex是否是當前值,來判斷顯示本地不同的圖片。我按照下面的寫法,頁面會報404找不到相應圖片地址。
 

<div class="tab-item" @click="tabIndex=0">
    <img :src="tabIndex == 0 ? '@/assets/imgs/liaotian2.png' : '@/assets/imgs/liaotian1.png'" alt="">
</div>

 報錯:


後來問了下同事,才得到解法。下面就簡單總結一下正確寫法:

靜態 賦【靜態url】地址:

<img src="@/assets/imgs/avatar.jpeg" >

動態 賦 【靜態url 】地址(原因不多贅述,可以去百度下import和require的區別):
vue中img的src和react中相似。
寫法①:

js: 
    import url_1 from "@/assets/imgs/liaotian1.png"
    import url_2 from "@/assets/imgs/liaotian2.png"

html:
    <img :src="url_1" alt="">
    <img :src="tabIndex == 0 ? url_1 : url_2 alt="">

寫法②: 

<img :src="require('@/assets/imgs/avatar.jpeg')" >

 


所以,我的專案中可以根據狀態判斷img的src值,程式碼如下:

<div class="tab-section">
    <div class="tab-item" @click="tabIndex=0">
        <img :src="tabIndex == 0 ? require('@/assets/imgs/liaotian2.png') : require('@/assets/imgs/liaotian1.png')" alt="">
    </div>
    <div class="tab-item" @click="tabIndex=1">
        <img :src="tabIndex == 1 ? require('@/assets/imgs/lishi2.png') : require('@/assets/imgs/lishi1.png')" alt="">
    </div>
    <div class="tab-item" @click="tabIndex=2">
        <img :src="tabIndex == 2 ? require('@/assets/imgs/jiqi2.png') : require('@/assets/imgs/jiqi1.png')" alt="">
    </div>
</div>