无法在 Vue.js + webpack 中动态传递 imgs 的相对 src 路径 [英] Can't dynamically pass relative src path for imgs in Vue.js + webpack

查看:26
本文介绍了无法在 Vue.js + webpack 中动态传递 imgs 的相对 src 路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的问题是在 webpack 中使用 vue.js.

The issue I'm having is using vue.js with webpack.

我有一个列表,我想在 vue.js 中动态填充.

I have a list that I want to dynamically populate in vue.js.

我使用 v-for 遍历每个对象并创建列表项.

I am using v-for to iterate over each object and create the list items.

将 img src 标签绑定到数据点 {{resource.img}} 看起来像这样:<img v-bind:src="resource.img"> 动态加载一张图片.

To bind a img src tag to data point {{resource.img}} it looks like this: <img v-bind:src="resource.img"> to dynamically load an image.

然而,当客户端渲染页面时,src路径是正确的,但它是实际的相对路径(例如../assets/example.png"等,而不是webpack输出的路径.因此,图像创建 404,因为../assets/example.png"中没有图像.

However, when the client renders the page, the src path is correct, however it is the actual relative path (e.g. "../assets/example.png" etc, instead of the path webpack outputs. Thus, the image creates a 404 because there is no image at "../assets/example.png".

或者,如果我对图像加载的 src 进行硬编码,而 src 是 webpack 创建的某个路径,以找到正确的图像.

Alternatively, if I hardcode the src the image loads, and the the src is some path that webpack created, finding the correct image.

如何使用 webpack 和 vue.js 动态设置 src?

How can I dynamically set the src with webpack and vue.js?

推荐答案

你需要 require.context.

例如:

<img width="30" height="30" :src="imgUrl(resource.img)">

<小时>

var images = require.context('../../assets/img/', false, /\.jpg$/)

export default {
  methods: {
    imgUrl: function (path) {
      return images('./' + path)
    }
  }
}

对于在源文件夹中找到的任何图像,require.context 基本上会将源路径映射到构建目录中的最终路径.这就是 imgUrl() 方法在运行时返回正确路径的方式.

The require.context will essentially map the source path to the final path in the build directory for any image that it found in the source folder. This is how the imgUrl() method will return the right path at runtime.

这篇关于无法在 Vue.js + webpack 中动态传递 imgs 的相对 src 路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆