乐闻世界logo
搜索文章和话题

Vue cli 3 – how to use background image in style tag

1个答案

1

When using Vue CLI 3, applying background images to styles typically involves several steps, primarily focusing on correctly importing image paths into your Vue components. Here is a clear step-by-step solution along with a simple example to demonstrate how to implement this in a Vue project.

Step 1: Prepare Your Image Resources

First, ensure your image resources are placed in the appropriate directory of your project, typically within the src/assets folder. For example, you have an image named background.jpg.

Step 2: Import the Image into Your Component

In your Vue component, you can use the require method to import the image. This is because Vue CLI uses Webpack as its underlying bundling tool, which can handle various static resource references.

vue
<template> <div class="background-image"> <!-- Other component content --> </div> </template> <script> export default { // Component data and methods }; </script> <style scoped> .background-image { background-image: url('~@/assets/background.jpg'); height: 100vh; background-size: cover; background-position: center; } </style>

Explanation

In the above example, the .background-image class uses the background-image CSS property to set the background image. The key point is the image path:

  • Using ~ denotes a module request, instructing Webpack to resolve it.
  • @ represents the src directory, which is an alias in Vue CLI projects.
  • /assets/background.jpg is the path to the image within the src directory.

Summary

The benefit of this approach is that it leverages Webpack's capabilities to automatically optimize image resources, such as reducing file sizes and converting image formats, which can improve the final application's performance. Additionally, using Webpack to handle images provides benefits like cache optimization.

2024年7月12日 17:07 回复

你的答案