"; 2. Use import to introduce the image; 3. Use require to load dynamically; 4. Introduce "publicPath" and splice it into the path to achieve dynamic changes in the introduced path."/> "; 2. Use import to introduce the image; 3. Use require to load dynamically; 4. Introduce "publicPath" and splice it into the path to achieve dynamic changes in the introduced path.">
search
HomeWeb Front-endFront-end Q&AHow to replace local images in Vue

How to replace local images in Vue

Jan 29, 2023 am 10:36 AM
vuepicture

Vue method to replace local images: 1. Convert the image to base64 format through ""; 2. Use import to introduce the image; 3. Use require to dynamically load; 4. Introduce "publicPath" and splice it in In the path, it is enough to realize the dynamic change of the introduced path.

How to replace local images in Vue

The operating environment of this tutorial: Windows 10 system, vue3 version, DELL G3 computer

How to replace local images with Vue?

vue dynamically loads local images

Today I encountered a problem of introducing local images into the vue file, so I came up with this article.

Usually, one of our img tags is written like this in html:

<img  src="/static/imghwm/default1.png" data-src="../images/demo.png" class="lazy" alt="How to replace local images in Vue" >

This way of writing can only reference pictures under relative paths. Absolute paths cannot be used. If you use an absolute path, such resources will be copied directly without being processed by webpack.

If src is a variable, we usually set a variable src in data for dynamic binding.

<img  src="/static/imghwm/default1.png" data-src="src" class="lazy" alt="How to replace local images in Vue" >//data中定义变量src
data() {
  return {
    src: '../images/demo.png' 
  }
}

However, at this time, you will find that the image has not been loaded and the image is not displayed. By checking, it is found that the address of this image is ../images/ demo.png, that is to say, the relative path bound through v-bind will not be processed by webpack's file-loader, and will only undergo simple text replacement.

then what should we do?

Solution

1. Convert the image to **base64**format

<img  src="/static/imghwm/default1.png" data-src="data:image/png;base64,iVBYKIGloxxxxxxxxxxxxxxxxxxx..." class="lazy" alt="How to replace local images in Vue" >

Generally, you can do this if the pictures are relatively small, such as icons, etc. The size is generally within 10KB.

2. Use **import** to introduce images

<img  src="/static/imghwm/default1.png" data-src="src" class="lazy" alt="How to replace local images in Vue" >//使用import引入
import img from '../images/demo.png'

//data中定义变量src
data() {
  return {
    src: img 
  }
}

3. Use **require** to dynamically load

<img  src="/static/imghwm/default1.png" data-src="src" class="lazy" alt="How to replace local images in Vue" >//data中定义变量src
data() {
  return {
    src: require('../images/demo.png')
  }
}

4. Introduce **publicPath**And splice it into the path to realize dynamic changes of the imported path

<img  src="/static/imghwm/default1.png" data-src="publicPath + 'images/demo.jpg'" class="lazy" alt="How to replace local images in Vue" > // √
// 编译后:<img  src="/static/imghwm/default1.png" data-src="/foo/images/demo.jpg" class="lazy" alt="How to replace local images in Vue" ><script>export default:{
    data(){
        return {
          publicPath: process.env.BASE_URL,
        }
    },}</script>

In vue.config.js Configuration in publicPathPath:

//vue.config.jsmodule.exports = {
    publicPath:'/foo/',
    ...}

结论

静态资源可以通过两种方式进行处理:

  • 在 JavaScript 被导入或在 template/CSS 中通过相对路径被引用。这类引用会被 webpack 处理。

  • 放置在 public 目录下或通过绝对路径被引用。这类资源将会直接被拷贝,而不会经过 webpack 的处理。

原理

从相对路径导入

当你在 JavaScript、CSS 或 *.vue 文件中使用相对路径 (必须以 . 开头) 引用一个静态资源时,该资源将会被包含进入 webpack 的依赖图中。

在其编译过程中,所有诸如 <img src="/static/imghwm/default1.png" data-src="..." class="lazy" alt="How to replace local images in Vue" >background: url(...) 和 CSS @import 的资源 URL 都会被解析为一个模块依赖

绝对路径引入时,路径读取的是public文件夹中的资源,任何放置在 public 文件夹的静态资源都会被简单的复制到编译后的目录中,而不经过 webpack特殊处理。

当你的应用被部署在一个域名的根路径上时,比如http://www.abc.com/,此时这种引入方式可以正常显示但是如果你的应用没有部署在域名的根部,那么你需要为你的 URL 配置 publicPath 前缀,publicPath 是部署应用包时的基本 URL,需要在 vue.config.js 中进行配置。

扩展

关于vue file-loader vs url-loader

如果我们希望在页面引入图片(包括img的src和background的url)。当我们基于webpack进行开发时,引入图片会遇到一些问题。

其中一个就是引用路径的问题。拿background样式用url引入背景图来说,我们都知道,webpack最终会将各个模块打包成一个文件,因此我们样式中的url路径是相对入口html页面的,而不是相对于原始css文件所在的路径的。这就会导致图片引入失败。这个问题是用file-loader解决的,file-loader可以解析项目中的url引入(不仅限于css),根据我们的配置,将图片拷贝到相应的路径,再根据我们的配置,修改打包后文件引用路径,使之指向正确的文件。
另外,如果图片较多,会发很多http请求,会降低页面性能。这个问题可以通过url-loader解决。url-loader会将引入的图片编码,生成dataURl。相当于把图片数据翻译成一串字符。再把这串字符打包到文件中,最终只需要引入这个文件就能访问图片了。当然,如果图片较大,编码会消耗性能。因此url-loader提供了一个limit参数,小于limit字节的文件会被转为DataURl,大于limit的还会使用file-loader进行copy。

url-loader和file-loader是什么关系呢?简答地说,url-loader封装了file-loader。url-loader不依赖于file-loader,即使用url-loader时,只需要安装url-loader即可,不需要安装file-loader,因为url-loader内置了file-loader。通过上面的介绍,我们可以看到,url-loader工作分两种情况:1.文件大小小于limit参数,url-loader将会把文件转为DataURL;2.文件大小大于limit,url-loader会调用file-loader进行处理,参数也会直接传给file-loader。因此我们只需要安装url-loader即可。

原文链接:cnblogs.com/weizaiyes/p

关于background url引入图片时

按照上面理论,如果我采用相对路径的方式引入图片的话,webpack会对其require处理。

background: url('./iphonexs.png') 0 0 no-repeat;

实际上确实如此,我看到页面的背景变成:

background: url(/resources/dist/images/iphonexs.a25bee7.png) 0 0 no-repeat;

这是根据url-loader的配置处理的结果。【推荐学习:《vue视频教程》】

或者采用动态style的方式:

<div></div>

The above is the detailed content of How to replace local images in Vue. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
React: The Foundation for Modern Frontend DevelopmentReact: The Foundation for Modern Frontend DevelopmentApr 19, 2025 am 12:23 AM

React is a JavaScript library for building modern front-end applications. 1. It uses componentized and virtual DOM to optimize performance. 2. Components use JSX to define, state and attributes to manage data. 3. Hooks simplify life cycle management. 4. Use ContextAPI to manage global status. 5. Common errors require debugging status updates and life cycles. 6. Optimization techniques include Memoization, code splitting and virtual scrolling.

The Future of React: Trends and Innovations in Web DevelopmentThe Future of React: Trends and Innovations in Web DevelopmentApr 19, 2025 am 12:22 AM

React's future will focus on the ultimate in component development, performance optimization and deep integration with other technology stacks. 1) React will further simplify the creation and management of components and promote the ultimate in component development. 2) Performance optimization will become the focus, especially in large applications. 3) React will be deeply integrated with technologies such as GraphQL and TypeScript to improve the development experience.

React: A Powerful Tool for Building UI ComponentsReact: A Powerful Tool for Building UI ComponentsApr 19, 2025 am 12:22 AM

React is a JavaScript library for building user interfaces. Its core idea is to build UI through componentization. 1. Components are the basic unit of React, encapsulating UI logic and styles. 2. Virtual DOM and state management are the key to component work, and state is updated through setState. 3. The life cycle includes three stages: mount, update and uninstall. The performance can be optimized using reasonably. 4. Use useState and ContextAPI to manage state, improve component reusability and global state management. 5. Common errors include improper status updates and performance issues, which can be debugged through ReactDevTools. 6. Performance optimization suggestions include using memo, avoiding unnecessary re-rendering, and using us

Using React with HTML: Rendering Components and DataUsing React with HTML: Rendering Components and DataApr 19, 2025 am 12:19 AM

Using HTML to render components and data in React can be achieved through the following steps: Using JSX syntax: React uses JSX syntax to embed HTML structures into JavaScript code, and operates the DOM after compilation. Components are combined with HTML: React components pass data through props and dynamically generate HTML content, such as. Data flow management: React's data flow is one-way, passed from the parent component to the child component, ensuring that the data flow is controllable, such as App components passing name to Greeting. Basic usage example: Use map function to render a list, you need to add a key attribute, such as rendering a fruit list. Advanced usage example: Use the useState hook to manage state and implement dynamics

React's Purpose: Building Single-Page Applications (SPAs)React's Purpose: Building Single-Page Applications (SPAs)Apr 19, 2025 am 12:06 AM

React is the preferred tool for building single-page applications (SPAs) because it provides efficient and flexible ways to build user interfaces. 1) Component development: Split complex UI into independent and reusable parts to improve maintainability and reusability. 2) Virtual DOM: Optimize rendering performance by comparing the differences between virtual DOM and actual DOM. 3) State management: manage data flow through state and attributes to ensure data consistency and predictability.

React: The Power of a JavaScript Library for Web DevelopmentReact: The Power of a JavaScript Library for Web DevelopmentApr 18, 2025 am 12:25 AM

React is a JavaScript library developed by Meta for building user interfaces, with its core being component development and virtual DOM technology. 1. Component and state management: React manages state through components (functions or classes) and Hooks (such as useState), improving code reusability and maintenance. 2. Virtual DOM and performance optimization: Through virtual DOM, React efficiently updates the real DOM to improve performance. 3. Life cycle and Hooks: Hooks (such as useEffect) allow function components to manage life cycles and perform side-effect operations. 4. Usage example: From basic HelloWorld components to advanced global state management (useContext and

React's Ecosystem: Libraries, Tools, and Best PracticesReact's Ecosystem: Libraries, Tools, and Best PracticesApr 18, 2025 am 12:23 AM

The React ecosystem includes state management libraries (such as Redux), routing libraries (such as ReactRouter), UI component libraries (such as Material-UI), testing tools (such as Jest), and building tools (such as Webpack). These tools work together to help developers develop and maintain applications efficiently, improve code quality and development efficiency.

React and Frontend Development: A Comprehensive OverviewReact and Frontend Development: A Comprehensive OverviewApr 18, 2025 am 12:23 AM

React is a JavaScript library developed by Facebook for building user interfaces. 1. It adopts componentized and virtual DOM technology to improve the efficiency and performance of UI development. 2. The core concepts of React include componentization, state management (such as useState and useEffect) and the working principle of virtual DOM. 3. In practical applications, React supports from basic component rendering to advanced asynchronous data processing. 4. Common errors such as forgetting to add key attributes or incorrect status updates can be debugged through ReactDevTools and logs. 5. Performance optimization and best practices include using React.memo, code segmentation and keeping code readable and maintaining dependability

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)