iT邦幫忙

0

Vue Component使用fetch讀入SVG inline問題

RC 2019-04-17 14:35:252120 瀏覽

因為svg檔案過大(>500k),不適合併入js,想要使用從src讀入svg整個內容。

vue-svg-spritevue-svg-loadervue-svg-inline-loader已試過,都是併入JS的方式

參考Jacky發表於Medium的方法〈Simple loading svg inline in Vue〉建立SvgInline.vue

<template>
    <span class="icon"></span>
</template>
<script>
let cache = new Map();
export default {
  props: {
    src: { type: String, required: true }
  },
  async mounted() {
    if (!cache.has(this.src)) {
      try {
        cache.set(this.src, fetch(this.src).then(r => r.text()));
      } catch (e) {
        cache.delete(this.src);
      }
    }
    if (cache.has(this.src)) {
      this.$el.innerHTML = await cache.get(this.src);
    }
  }
};
</script>

於view頁面上讀入svg

<template>
	<div>
		<svg-inline src="@/assets/img/svginlineitem.svg" />
	</div>
</template>

<script>
import SvgInline from '@/components/SvgInline.vue'

export default {
	components: {
		SvgInline
	}
}
</script>

svg圖片放置於assets/img資料夾內,會跟著webpack編譯而變動,但路徑部分始終無法變動。
請問是哪裡寫錯嗎?

marlin12 iT邦研究生 5 級 ‧ 2019-04-17 19:18:55 檢舉
如果你是用nuxt,就要把那個svg檔放在static資料夾內,然後把呼叫組件改為<svg-inline src="/svginlineitem.svg" />。
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
Peter Chen
iT邦新手 2 級 ‧ 2019-12-13 11:19:51

如果是用 Webpack 的話,下面這樣的寫法圖片不會被 Webpack 包進去:

<svg-inline src="@/assets/img/svginlineitem.svg" />

要改用下面的寫法:

<svg-inline :src="require('@/assets/img/svginlineitem.svg')" />

Require 的資源會被 webpack 取得並轉換成建置後的路徑

我要發表回答

立即登入回答