亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Vue 不加載動態 src 并且 require 不起作用

Vue 不加載動態 src 并且 require 不起作用

米琪卡哇伊 2022-12-18 16:39:32
我有一個問題,我想顯示一個動態 img 但如果我這樣寫:<img :src="src" alt="img">  它不起作用,相反,如果我這樣做它會起作用: <img src="../assets/img/banana.png" alt="img">我已經嘗試過 whit require 但它返回錯誤: Error: Cannot find module '../assets/img/banana.png'"
查看完整描述

1 回答

?
慕容森

TA貢獻1853條經驗 獲得超18個贊

問題是沒有關于模塊所在位置的信息,webpack 無法解析它。


不可能使用完全動態的導入語句,例如 import(foo)。因為 foo 可能是您系統或項目中任何文件的任何路徑。


import() 必須至少包含一些關于模塊所在位置的信息。


要解決此問題,您可以創建一個 BaseImage 組件來替換以特定路徑開頭的動態源,在本例../assets/中為 ,并讓 webpack 事先知道該信息。


IE。


<template>

  <img

    :src="computedSrc"

    :alt="alt"

    class="BaseImage"

    v-bind="$attrs"

    v-on="$listeners"

  />

</template>


<script>

export default {

  name: 'BaseImage',


  inheritAttrs: false,


  props: {

    src: {

      type: String,

      required: true,

    },


    /**

     * The alt tag is required for accessibility and SEO purposes.

     *

     * If it is a decorative image, which is purely there for design reasons,

     * consider moving it to CSS or using an empty alt tag.

     */

    alt: {

      type: String,

      required: true,

    },

  },


  computed: {

    // If the URL starts with ../assets/, it will be interpreted as a module request.

    isModuleRequest() {

      return this.src.startsWith('../assets/')

    },


    computedSrc() {

      // If it is a module request,

      // the exact module is not known on compile time,

      // so an expression is used in the request to create a context.

      return this.isModuleRequest

        ? require(`../assets/${this.src.replace('../assets/', '')}`)

        : this.src

    },

  },

}

</script>

替換img為BaseImage組件。


<!-- <img :src="img.src"  :alt="img.alt"> -->

<BaseImage :src="img.src" :alt="img.alt"/>

修改后的codeandbox


查看完整回答
反對 回復 2022-12-18
  • 1 回答
  • 0 關注
  • 442 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號