How to replace local images in Vue
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.
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="../images/demo.png">
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="src">//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="data:image/png;base64,iVBYKIGloxxxxxxxxxxxxxxxxxxx...">
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="src">//使用import引入 import img from '../images/demo.png' //data中定义变量src data() { return { src: img } }
3. Use **require
** to dynamically load
<img :src="src">//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="publicPath + 'images/demo.jpg'" alt=""> // √ // 编译后:<img src="/foo/images/demo.jpg" alt=""><script>export default:{ data(){ return { publicPath: process.env.BASE_URL, } },}</script>
In vue.config.js
Configuration in publicPath
Path:
//vue.config.jsmodule.exports = { publicPath:'/foo/', ...}
结论
静态资源可以通过两种方式进行处理:
- 在 JavaScript
被导入
或在 template/CSS 中通过相对路径
被引用。这类引用会被 webpack 处理。
- 放置在
public
目录下或通过绝对路径
被引用。这类资源将会直接被拷贝,而不会经过 webpack 的处理。
原理
从相对路径导入
当你在 JavaScript、CSS 或 *.vue
文件中使用相对路径 (必须以 .
开头) 引用一个静态资源时,该资源将会被包含进入 webpack 的依赖图中。
在其编译过程中,所有诸如 <img src="...">
、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即可。
原文链接:https://www.cnblogs.com/weizaiyes/p/7461967.html
关于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 :style="{'background': 'url(' + require('./iphonexs.png') + ') 0 0 no-repeat'}"></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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

There are three ways to refer to JS files in Vue.js: directly specify the path using the <script> tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses <router-link to="/" component window.history.back(), and the method selection depends on the scene.

You can query the Vue version by using Vue Devtools to view the Vue tab in the browser's console. Use npm to run the "npm list -g vue" command. Find the Vue item in the "dependencies" object of the package.json file. For Vue CLI projects, run the "vue --version" command. Check the version information in the <script> tag in the HTML file that refers to the Vue file.

Function interception in Vue is a technique used to limit the number of times a function is called within a specified time period and prevent performance problems. The implementation method is: import the lodash library: import { debounce } from 'lodash'; Use the debounce function to create an intercept function: const debouncedFunction = debounce(() => { / Logical / }, 500); Call the intercept function, and the control function is called at most once in 500 milliseconds.
