簡體   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