Front-end developers who use vue as the development technology stack often cooperate with front-end construction tools to carry out engineering management of the project. For example, the commonly used vue family bucket webpack solution is used to develop some medium and large front-end projects. With webpack, Vue's componentization advantages are more obvious. We can build front-end pages in work practice through single-file componentization development, thereby improving development efficiency. There is such a question: "When we write a vue single file, what are we writing?" Many people may answer this way: template is responsible for the template, javascript is responsible for the logic, and style is responsible for the style. When the answer reaches this point, a Vue developer's world view is basically very clear. All we have to do is write template, javascript, and style in a single file component. If we only limit ourselves to this, it is obvious that we cannot serve our entire development process from better utilization of single-file components. Next, I will discuss with you some methodological issues in vue single-file development.
The essence of vue single file
Vue single file is a file named with a specific file extension .vue
. The code shown below:
ListDemo.vue
<template> <div> <ul> <li>{{item.value}}</li> </ul> </div> </template> <script> export default { name: 'ListNav', data() { return { list: [ { key: 'home', value: '首页' }, { key: 'category', value: '文章分类' }, { key: 'tags', value: '标签' }, { key: 'about', value: '关于我' }, { key: 'links', value: '友情链接'}, ], }; }, }; </script> <style> .list-demo { font-size: 14px; } </style>
The code contains template, script, and style. The functions of the three will not be described in detail here. The above structure shows the basic file structure of a vue single file. The idea behind it is that a single file component corresponds to a functional component, and the template, style, and business logic of the component are all maintained nearby. From the perspective of component reusability and later maintainability, this concept has greatly improved the efficiency of component development. The single file of vue is neither js, html, nor css file. How such a file is applied to the page is a question that will be discussed below. How is the single file of vue processed into the page? Available resources.
vue single file processing process
vue single file cooperates with the webpack build tool and will be processed by vue-loader in webpack. As shown below:
{ test: /\.vue$/, loader: 'vue-loader', }
The vue single file introduced through import or require in the project will be processed by vue-loader. In this process, vue-loader will parse and process the template according to template, script and style. The results are returned, and three different types of files are handed over to the next loader for processing. If the single-file component is declared in components in the parent component, the corresponding item in components will be inserted into the parsed script code. This process starts from the entry file main.js
, and all involved single-file components that are dependent on it go through this process in turn. After that, all components will be instantiated according to the dependencies in the business logic. This process is also a method we often use in development. (You can pull up a separate article here to describe the processing process of vue-loader in detail)
Common postures for single files
Component references in templates
1. How to use
Splitting and nesting of components:
Divide specific business into smaller components according to functions and later reusability considerations
Integrate small functional components (subcomponents) through a container component (parent component)
Operation method: introduce subcomponents into parent components, components into components Register and add the corresponding component reference template in the template
This method is also a common method we use in single-file development. The instantiation of all components is implicit in the nested relationship of the components. and business logic. Developers only need to care about the introduction of the component, register the component in the parent component logic, and introduce the component as a tag in the template of the parent component. The instantiation timing of the components to be introduced in this process can also be controlled in the business logic through the v-if directive.
2. Applicable Scenarios
In most scenarios, we can carry out component development in this way. This model has a characteristic: the introduction of components is completed through component registration and writing the corresponding component tags in the template. Introducing components through tags in the template is essential. This feature may bring a certain amount of repetitive workload to developers in some business scenarios.
API-style calling
API-style calling refers to manually creating instances of subcomponents. There is no need to introduce components and template tag placeholders in the business logic. Control the components in the exposed API. Instantiation and display.
1. How to use
The function module provides an entrance js to control all the functional logic of the order file instance of the function module
-
When using this function module in other components, call the js under the function module and pass in some parameters
Operation method:
Confirm.vue
<template> <el-dialg> {{content}} <el-button>cancel</el-button> <el-button>ok</el-button> </el-dialg> </template> <script> export default { name: 'Confirm', data() { return { visible: false, content: '这是一个confirm dialog', callback: null, }; }, methods: { handleCancelClick() { this.callback('cancel'); }, handleOkClick() { this.callback('confirm'); }, }, }; </script>
confirm.js
import Vue from 'vue'; import Confirm from './confirm'; const ConfirmConstructor = Vue.extend(Confirm); const confirm = (content) => { let confirmInstance = new ConfirmConstructor({ data: { content, }, }); confirmInstance.vm = confirmInstance.$mount(); confirmInstance.vm.visible = true; // 手动插入目的 dom document.body.appendChild(confirmInstance.vm.$el); confirmInstance.vm.callback = action => { return new Promise((resolve, reject) => { resolve(action); }); }; return confirmInstance.vm; };
如上所示,给出的是一个确认弹框的场景实现。确认弹框在很多用户交互中是一个必须的交互形式。很多组件库也采用上面这种 API 式的组件调用。调用方仅仅通过 api 的调用,就能实现该功能模块的引用。这样就避免了在 template 中通过标签占位的方式引用。实现原理就是手动接管单文件组件的实例化,通过 Vue.extend 获得该组件对应的 Vue 的子类,在暴露给调用的 api 中去实例化这个组件。这个过程中我们可能还要完成一些组件数据的注入,逻辑相关以及手动将该组件插入到目的 dom 中。手动的注入 dom 是该种方式的一个很大特点,通过在 api 中动态的注入目的 dom,避免我们在各个业务组件中调用该功能模块时重复性的在业务组件 template 中手写组件标签。
二、适用场景
功能聚合度高,组件内逻辑简单,输入输出较为单一,比如一些功能较为独立的弹框
一些特殊的自定义指令开发,比如在一些特殊场景的指令,可以复用一些单文件组件,通过在指令的钩子中实例化组件对应的 vue 子类,按照特定的逻辑插入到目的 dom 中(例如:element-ui的v-loading)
区别和共性
共性:通过实例化对应组件完成组件的功能逻辑
区别:实例化的时机和方式不同。模板式的引入通过组件注册和标签引入的方式来使用单文件组件。标签引入解决了子组件插入的 dom 位置问题,开发者无需关心。API 式的单文件组件使用,在 API 调用时手动实例化组件,需要手动控制插入到目的 dom。
总结
vue 的单文件组件提供了 vue 的组件化开发思路,其本质在导出 vue 的一些关键属性,比如生命周期函数,methods,computed, watch,props等。我们可以通过上述两种方式来使用单文件组件,目的在于工程内部尽量减少重复的模板代码,组件解耦。
相关推荐:
webpack入坑之旅(五)加载vue单文件组件_html/css_WEB-ITnose
The above is the detailed content of Detailed introduction of single file in vue (code example). For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The 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 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 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 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.


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

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.

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

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