問題描述
我在 login.vue 組件所在的目錄中有一個圖像文件(以下代碼所在的位置).但是,當我嘗試此代碼時,圖像將無法加載:
I have an image file in the same directory as my login.vue component (which is where the following code is located). But, when I try this code, the image will not load:
<div background="benjamin-child-17946.jpg" class="login" style="height:100%;">
我收到此錯誤:
加載資源失敗:服務器響應狀態為 404(未找到)
Failed to load resource: the server responded with a status of 404 (Not Found)
這很奇怪,因為我可以在終端中看到我的圖像與 login.vue 位于同一目錄中.我正在使用 webpack 進行編譯.這可能是什么原因造成的?
This is strange, because I can see in my terminal that my image is in the same directory as login.vue. I am using webpack to compile. What might be causing this?
推薦答案
您的主要問題是編譯單個文件組件并且編譯后的腳本不太可能與您的圖像位于當前位置的同一目錄中.您的第二個問題是您沒有正確地將背景圖像分配給 div
.你應該使用 CSS.
Your primary issue is that single file components are compiled and the compiled script is very unlikely to reside in the same directory as the current location as your image. Your second issue is that you are not assigning the background image to your div
correctly. You should use CSS.
我建議您在電子應用程序(或資產或靜態或任何您想調用的名稱)的根目錄中創建一個 images
目錄.然后,您可以使用 file://
協議引用該目錄中的文件.
I would suggest that you make an images
directory in the root of your electron application (or assets or static or whatever you want to call it). Then, you can reference files in that directory using the file://
protocol.
其次,我建議您定義一個 CSS 類并使用它.因此,在您的單個文件組件中,定義此樣式部分:
Second, I would recommend you define a CSS class and use that. So, in your single file component, define this style section:
<style>
.background {
background: url('file:///images/benjamin-child-17946.jpg') no-repeat center center fixed;
background-size: cover
}
</style>
在你的 div 上使用類.
And on your div just use the class.
<div class="login background">
最后,您還可以使用 webpack 的 url-loader
將文件加載為 dataUrl
但我建議作為更高級的練習并堅持簡單暫時.
Finally, you could also use webpack's url-loader
to load the file as a dataUrl
but I would recommend that as a more advance exercise and just stick with the simple for now.
編輯
我使用 electron-vue 從頭開始??創建了一個項目,它使用了 webpack,我確實遇到了上面使用 file://
協議的錯誤,我在不使用 webpack 時不會遇到.使用上面的模板,而不是使用file:///images/benjamin-child-17946.jpg
,把文件放到static
目錄下,使用/static/benjamin-child-17946.jpg代碼>.這允許
vue-loader
正常工作.
I created a project from scratch using electron-vue which uses webpack and I did run into an error with the above using the file://
protocol, that I don't run into when not using webpack. With the above template, instead of using
file:///images/benjamin-child-17946.jpg
, put the file in the static
directory and use /static/benjamin-child-17946.jpg
. That allows vue-loader
to work properly.
如果你沒有使用 electron-vue
,那么你的 webpack 配置可能會有所不同.
If you are not using electron-vue
, then your webpack configuration may be different.
這篇關于背景圖像未在電子應用程序中加載的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!