This article mainly introduces you to the relevant information about reference path processing in vue single files. The article introduces it in detail through sample code. It has certain reference learning value for everyone to learn or use vue.js. Friends who need it Let’s learn together with me.
Preface
Vue's single file component is very commonly used when using Vue, and in the development process of vue single file, in the single file The template may involve the processing of file paths, such as
, the processing of background in style, etc. The following discusses the src processing of
in several different scenarios, and explains how to correctly reference static resources (such as image processing) during the development process using vue webpack.
As shown below, the following single file component provides examples of referencing image paths in different scenarios (image static resources are stored in src/assets/small.png):
<template>
<p id="app">
<!-- 1. 模版中src选项直接写相对路径 -->
<img src="/static/imghwm/default1.png" data-src="./assets/small.png" class="lazy" alt="图片相对路径测试">
<!-- 2. 模版中src选项绑定相对路径字符串 -->
<img src="/static/imghwm/default1.png" data-src="relative_img" class="lazy" : alt="图片相对路径测试">
<!-- 3. 模版中src选项绑定html绝对路径字符串 -->
<img src="/static/imghwm/default1.png" data-src="absolute_img" class="lazy" : alt="图片绝对路径测试">
<!-- 4. 模版中src选项绑定手动加载的图片资源 -->
<img src="/static/imghwm/default1.png" data-src="smallImg" class="lazy" : alt="图片资源测试">
</p>
</template>
<script>
import smallImg from './assets/small.png';
export default {
name: 'app',
data() {
return {
smallImg: smallImg,
relative_img: './assets/small.png',
absolute_img: '/static/img/small.png',
};
},
}
</script>The above code snippets give four scenarios of how to use the img tag to reference image resources in the Vue single file component. Of course, not all of these four methods can load image resources correctly.
Case 1:
Bind directly to the src attribute with a relative path in the template. In this case, the image resource can be loaded correctly. We know that in the process of webpack processing vue single file components, vue-loader is mainly responsible for processing *.vue files. The vue-loader resource path processing section in the vue-loader documentation explains how vue-loader handles resource paths in templates. For example:
, background: url(), @import, etc. will be processed as module dependencies. That is to say, in these cases, vue-loader automatically handles the resource reference of the path and the final path replacement. The processing of img is as follows:
<img src="/static/imghwm/default1.png" data-src="./logo.png" class="lazy" alt="What are the methods for reference paths in Vue single files?" >
will be compiled by the vue template compiler into:
createElement('img', { attrs: { src: require('./logo.png') }})This also explains why the image content can be displayed correctly in case 1, because vue-loader Automatically help us with resource introduction and path replacement.
Case 2:
The relative path string variable is bound to the src attribute in the template. In this case, the image cannot be displayed normally. . The reason is that vue-loader cannot identify whether the variable is a path string, so there is no problem of vue-loader automatically introducing resources and path replacement. In this case, the compiled template is still a relative path string. Obviously, without the corresponding resource introduction and wrong path, the image cannot be displayed correctly.
Situation 3:
Many people try to use absolute path variables to import while relative paths cannot be displayed correctly. Obviously, this In this case, the image cannot be displayed because the image resource has not been manually introduced. Note: Many students try to manually introduce resources and then bind src according to the absolute path variable. They find that there are indeed referenced resources under the dist/static/img/ path, but the url-loader in the vue-cli webpack template does not work for img type files. When loading, the processing of hash values is added. In this case, even if we bind an absolute path variable, we still cannot correctly reference the image because it cannot correctly match the image file to which the hash value is added. In this case where images need to be introduced manually, the approach to situation 4 is recommended.
Case 4:
The src attribute in the template is directly bound to the manually introduced image resource. In this case, the image can be displayed correctly. . This method is also used by vue-loader when processing resources corresponding to automatically imported paths.
To sum up, in the vue single file component, the key to correctly displaying an image is:
The image resource is required or imported, that is, it will be used by webpack's url -loader is processed to the final directory
img src attribute needs to be replaced with the final image resource path
The above two points are indispensable. . The reason why the picture can be displayed correctly in case one and case four is that the above two conditions are met in both cases. In case one, vue-loader automatically does this for us, and in case four, we do it manually.
Problems that may be encountered during development:
During development, you may encounter a scenario where a picture list is rendered in a loop. According to the above summary , we can construct an array of image information objects, such as:
<template>
<p id="app">
<!-- 1. 模版中 src 选项直接写相对路径 -->
<img src="/static/imghwm/default1.png" data-src="./assets/small.png" class="lazy" alt="图片相对路径测试">
<!-- 2. 模版中 src 选项绑定相对路径字符串 -->
<img src="/static/imghwm/default1.png" data-src="relative_img" class="lazy" : alt="图片相对路径测试">
<!-- 3. 模版中 src 选项绑定绝对路径字符串 -->
<img src="/static/imghwm/default1.png" data-src="absolute_img" class="lazy" : alt="图片绝对路径测试">
<!-- 4. 模版中 src 选项绑定手动加载的图片资源 -->
<img src="/static/imghwm/default1.png" data-src="smallImg" class="lazy" : alt="图片测试">
<!-- 5. 循环加载图片资源示例 -->
<img src="/static/imghwm/default1.png" data-src="image.src" class="lazy"
v-for="image in imgList"
:key="image.id"
:
:alt="image.title">
</p>
</template>
<script>
import smallImg from './assets/small.png';
import bigImg from './assets/big.jpg';
export default {
name: 'app',
data() {
return {
smallImg: smallImg,
relative_img: './assets/small.png',
absolute_img: '/static/img/small.png',
imgList: [
{ id: 1, title: 'test1', src: require('./assets/logo1.png') },
{ id: 2, title: 'test2', src: require('./assets/logo2.png') },
{ id: 3, title: 'test3', src: require('./assets/logo3.png') },
],
};
},
}
</script>In this way, we can perfectly display the images we render in a loop.
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
Using the input box to find keywords in jquery
How to implement the specified assignment method using js and jQuery
The above is the detailed content of What are the methods for reference paths in Vue single files?. For more information, please follow other related articles on the PHP Chinese website!
JavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AMThe main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.
Understanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AMUnderstanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft






