Skip to main content

常見問題

寫 vue3 常遇到的問題

取得靜態支援

以前 Vue2

const imgUrl = require("~/assets/img.png");

但是現在改用 vite 了,所以這個方法不再支援。可以使用 new URL(url, import.meta.url).href 來動態引入靜態資源是可行的。以下是一些要點:

1. new URL 動態引入靜態資源

在 Nuxt3 的 SSR 模式中,可以使用 new URL(url, import.meta.url).href 來動態引入靜態資源,例如:

const imageUrl = new URL("../../assets/image.png", import.meta.url).href;

這樣可以獲得靜態資源的正確路徑,不會受到 content-security-policy 的影響。[5]

caution

在 Nuxt3 的 CSR 模式中,使用 new URL(url, import.meta.url).href 或相對路徑引入靜態資源是可行的, 在 SSR 模式下可能會導致問題。

2. 使用相對路徑引入靜態資源

另一個選擇是將需要動態加載的靜態資源放在 public 目錄下,然後使用相對路徑引入,例如:

<img src="/image.png" alt="Image" />

這樣在 SSR 和 CSR 模式下都能正常工作,不需要擔心路徑問題。[5]

Citations:

[1] https://hackmd.io/%40Yan06/SJgkRrhej

[2] https://wayne-blog.com/2023-01-14/nuxt-try-nuxt3/

[3] https://ithelp.ithome.com.tw/articles/10308008

[4] https://blog.csdn.net/qq_42177478/article/details/108578105

[5] https://juejin.cn/post/7249205118533009469