背景图像未在电子应用程序中加载

2022-01-10 00:00:00 electron html css vue.js webpack

我在 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.

相关文章