问题:我想根据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>

 

Logo

前往低代码交流专区

更多推荐