繁体   English   中英

在 VueJS 中使用'require'显示图片时如何保存图片链接?

[英]How to save image link in when using 'require' to display image in VueJS?

我正在尝试创建一个页面,在其中显示带有图像的 Pizza 项目。 披萨 object 保存在数据库中,字段imgUrl 图像没有显示,但我看到了我提供的alt文本,但我可以在控制台中看到图像链接是正确的。

现在,数据库中的 imgUrl 字段有类似../assets/images/pizza.jpg的数据。 我应该改为在数据库中保存require(../assets/images/pizza.jpg) 这看起来很奇怪。 下面是代码,请看mounted方法。

<template>
  <div>
    <div class="class">
      <span><h1>All you can eat Menu.</h1></span>
      <div class="container">
        <div class="box" v-for="item in pizzaList" :key="item.id">
          <div>
            <img :src="item.imgUrl" alt="Image"/>
              <div>
                <a class="btn" @mouseenter="$event.currentTarget.style.background = '#EF6B7F'"
                @mouseleave="$event.currentTarget.style.background = '#e31837' ">Buy Now</a>
              </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data () {
    return {
      pizzaList: []
    }
  },
  mounted: function () {
    axios.get('http://localhost:8081/api/pizza/all')
    .then(response => {
      this.pizzaList = response.data;
    })
    .catch(e => {
      console.log(e);
    })
  }
}
</script>

我已经阅读了Vue 和 API:Displaying Image Image path in Vue JS How to reference static assets within vue javascript

但是这些答案告诉我们的是当我们对 url 进行硬编码时该怎么做,我们应该用require封装它但是他们没有告诉我们何时从数据库获取链接,我们如何将require放入 html 标签中。 我希望我的问题很清楚。 如有需要请询问详情。 谢谢

它不起作用的原因是因为

Webpack's require() needs at least some part of the file path to be completely static and we should "make only part of the path dynamic"

这意味着您不能将整个图像路径放在数据库中,并在 UI 中将其传递给require并期望它工作

我换了

<img :src="require(`${item.imgUrl}`)" alt="Image"/>

其中 item.imgUrl = ' ../assets/entities/pizza/pizza_1.jpg '(这是相对于组件的整个图像路径)

经过

<img :src="require(`../assets${item.imgUrl}`)" alt="Image"/>

其中 item.imgUrl = ' /entities/pizza/pizza_1.jpg '

Michal Levy在评论中提到的这个答案解释了这一切https://stackoverflow.com/a/64208406/8147680

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM