日常总结——vue+webpack图片动态绑定路径

问题

使用 vue + webpack 构建项目时,如果直接动态绑定 img 来源(如下),图片会404
template中:

<div class="citeMethod">
    <div>意向位置:</div>
    <ul>&nbsp;
        <li v-for="item in citeMethodList">{{item}}<img :src="imgsrc" class="arrow"/></li>
    </ul>
</div>

导出:

export default{
    data(){
        return{
            citeMethodList: ['区域找房', '地铁找房', '环线找房'],
            imgsrc: '../../../img/nav_col.svg',
        }
    }
}

运行之后,浏览器找不到图片
这里写图片描述
浏览器warning:
这里写图片描述

分析、查找原因

如果在 template 中直接引入图片

<div class="citeMethod">
    <div>意向位置:</div>
    <ul>&nbsp;
        <li v-for="item in citeMethodList">{{item}}<img src="../../../img/nav_col.svg" class="arrow"/></li>
    </ul>
</div>

webpack打包后路径为
这里写图片描述

展示效果为:
这里写图片描述

可以看到,这里,webpack打包时便引入了图片,所以可以显示

因而可以判断,404 的原因为:webpack 没有打包图片,localhost运行之后,路径为服务器路径,所以找不到文件
 

解决方法

找到了原因,就等于找到了解决方法 —— 在准备数据时,便将 svg 文件引入进来

写法一:使用 commonjs 同步语法 require 引入依赖
template

<div class="citeMethod">
    <div>意向位置:</div>
    <ul>&nbsp;
        <li v-for="item in citeMethodList">{{item}}<img :src="imgsrc" class="arrow"/></li>
    </ul>
</div>

导出

export default{
    data(){
        return{
            citeMethodList: ['区域找房', '地铁找房', '环线找房'],
            imgsrc: require('../../../img/nav_col.svg'),
        }
    }
}

写法二:使用 import 将文件引入后赋予变量,使用变量动态绑定
template

<div class="citeMethod">
    <div>意向位置:</div>
    <ul>&nbsp;
        <li v-for="item in citeMethodList">{{item}}<img :src="imgsrc" class="arrow"/></li>
    </ul>
</div>

导出

import NavCol from '../../../img/nav_col.svg'
export default{
    data(){
        return{
            citeMethodList: ['区域找房', '地铁找房', '环线找房'],
            imgsrc: NavCol,
        }
    }
}

好了,问题完美解决!
至于为什么 ul 中要放一个空字符——空格,是为了文字垂直居中对齐,至于具体原因,那是另一说啦,后面可能会写一篇总结哟,好奇的小伙伴可以先百度一下垂直对齐的基线问题~

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值