今天在 vue 文件中动态引入本地图片时发现路径没有问题但是一直 404
template 部分如下,使用 v-for 动态加载,数据存储在 setup 中的 nearbyItems 数组内
<template> <div class="nearby"> <div class="title">附近店铺</div> <div v-for="item in nearbyItems" :key="item.id" class="nearby-item"> <div class="left"> <img :src="item.logo" alt="" class="shop-logo" /> </div> <div class="right"> <div class="shop-title">{{ item.title }}</div> <div class="tags"> <span v-for="(tag, index) of item.tags" :key="index" class="tag-item">{{ tag }}</span> </div> <div class="promotion">{{ item.promotion }}</div> </div> </div> </div> </template>
script 部分代码如下
<script> export default { name: "Nearby", setup(){ const nearbyItems = [ { id: 1, logo: "../../assets/img/shop-logo.png", title: "永辉超市", tags: ["月售一万+","起送¥0","基础运费¥5"], promotion: "VIP尊享满89元减4元运费券(每月3张)", }, { id: 2, logo: "../../assets/img/shop-logo.png", title: "永辉超市", tags: ["月售一万+","起送¥0","基础运费¥5"], promotion: "VIP尊享满89元减4元运费券(每月3张)", }, { id: 3, logo: "../../assets/img/shop-logo.png", title: "永辉超市", tags: ["月售一万+","起送¥0","基础运费¥5"], promotion: "VIP尊享满89元减4元运费券(每月3张)", }, { id: 4, logo: "../../assets/img/shop-logo.png", title: "永辉超市", tags: ["月售一万+","起送¥0","基础运费¥5"], promotion: "VIP尊享满89元减4元运费券(每月3张)", }, { id: 5, logo: "../../assets/img/shop-logo.png", title: "永辉超市", tags: ["月售一万+","起送¥0","基础运费¥5"], promotion: "VIP尊享满89元减4元运费券(每月3张)", }, { id: 6, logo: "../../assets/img/shop-logo.png", title: "永辉超市", tags: ["月售一万+","起送¥0","基础运费¥5"], promotion: "VIP尊享满89元减4元运费券(每月3张)", }, { id: 7, logo: "../../assets/img/shop-logo.png", title: "永辉超市", tags: ["月售一万+","起送¥0","基础运费¥5"], promotion: "VIP尊享满89元减4元运费券(每月3张)", }, ]; return{ nearbyItems, } } } </script>
图片并没有加载出来,查看图片的地址显示 ../../assets/img/shop-logo.png ,通过v-bind 绑定的相对路径并不会被 webpack 的 file-loader 处理,只会做简单的文本替换,
常用的解决办法:
1. 使用 import 引入图片
<img :src="src"> //使用import引入 import img from '../images/demo.png' //data中定义变量src data() { return { src: img } }
2. 使用 require 动态加载
<img :src="src"> //data中定义变量src data() { return { src: require('../images/demo.png') } }
3. 较小的图片可以转为 base64 格式
结论:静态资源可以通过两种方式进行处理:
1.在JavaScript 被导入或在 template/CSS 中通过 相对路径被引用,这类引用会被 webpack 处理
2. 放置在 public 目录下通过绝对路径被引用,这类资源会被直接 copy ,不会经过 webpack 的处理
标签:shop,Vue,img,..,运费,404,logo,png,加载 From: https://www.cnblogs.com/geol4/p/17984805