Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of lightweight and efficient Front-end Modularization Scheme of Vue.js

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

The purpose of this article is to share with you the content of the example analysis of the lightweight and efficient front-end componentization scheme of Vue.js. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

The original intention of development

At the end of 2013, I was still working at Google Creative Lab. I used Angular for a period of time in the project, and while lamenting the productivity gains brought about by data binding, I also felt that the API design of Angular was too cumbersome, making the learning curve steep. Curious about the principle of Angular data binding, I began to "build wheels" and implemented a very crude data binding library based on dependency collection. This is the predecessor of Vue.js. At the same time, in the actual development, I found that the user interface can be described by a nested component tree, and a component can correspond to the ViewModel in MVVM. So I decided to improve my data binding experiment into a real open source project, the core idea of which is "data-driven component system".

MVVM data binding

The essence of MVVM is to link View and Model through data binding, so that changes in data are automatically mapped to view updates. Vue.js draws on the instruction mechanism of Angular in the API design of data binding: users can implement data binding through HTML attributes with special prefixes, or they can use common curly braces template interpolation, or use two-way binding on form elements:

{{msg}}

Interpolation is essentially an instruction, just to facilitate the writing of the template. During the compilation of the template, Vue.js creates an instruction object for each DOM node that needs to be dynamically updated. Whenever the data observed by an instruction object changes, it will perform the corresponding DOM operation on the bound target node. Instruction-based data binding makes the specific DOM operations reasonably encapsulated in the instruction definition, and the business code only needs to involve templates and operations on the data state, which greatly improves the development efficiency and maintainability of the application.

Unlike Angular, Vue.js 's API does not have complicated concepts such as module, controller, scope, factory, service, and so on. Everything is based on "ViewModel instance":

{{msg}} / / the native object is the data var data = {msg: 'hellogged'} / / create an ViewModel instance var vm = new Vue ({/ / Select the target element el:'# app', / / provide the initial data data: data})

Render the result:

Hello!

At the same time of rendering, Vue.js has also completed the dynamic binding of data: if you change the value of data.msg, DOM will be updated automatically. Is it very easy to understand? In addition, Vue.js has also greatly simplified the API of custom instructions and filters. If you have Angular development experience, you will get started very quickly.

Realization of data observation

The principle of data observation in Vue.js is essentially different from that in Angular. Readers who know about Angular may know that Angular's data observation uses a dirty check (dirty checking) mechanism. Each instruction will have a corresponding object to observe the data, called watcher;, and there will be many watcher in a scope. Whenever the interface needs to be updated, Angular iterates through all the watcher in the current scope, evaluates them one by one, and compares them with the previously saved old values. If the result of the evaluation changes, the corresponding update is triggered, a process called digest cycle. There are two problems with dirty inspection:

1. Any data change means that every watcher in the current scope needs to be re-evaluated, so when the number of watcher is large, the performance of the application will inevitably be affected, and it is difficult to optimize.

two。 When the data changes, the framework can not actively detect the change, and the digest cycle needs to be triggered manually to trigger the corresponding DOM update. Angular avoids this problem by automatically triggering digest cycle in the DOM event handler, but there are still many situations that require users to trigger manually.

Vue.js adopts an observation mechanism based on dependency collection. In principle, it is the same as the old MVVM framework Knockout. The basic principles of dependency collection are:

1. Transform the original data into "observable objects". An observable object can be valued or assigned.

two。 During the evaluation of watcher, each observable object that is valued registers the current watcher as its own subscriber and becomes a dependency of the current watcher.

3. When a dependent observable object is assigned, it notifies all subscribers of their own watcher re-evaluation and triggers the corresponding update.

4. The advantage of relying on collection is that it can track the changes of data accurately and actively, and there are no two problems of dirty checking mentioned above. However, the traditional dependency collection implementation, such as Knockout, usually needs to wrap the native data to create observable objects, and it needs to be in the form of function calls when taking and assigning values, which is tedious and not intuitive when operating data. At the same time, the object support for complex nested structures is not ideal.

Vue.js uses ES5's Object.defineProperty method to directly transform the properties of native data objects into getter and setter, which can collect and trigger dependencies inside these two functions, and perfectly support nested object structures. For arrays, listen for changes in the array through mutable methods of wrapping the array, such as push. This makes almost no difference between manipulating Vue.js data and manipulating native objects. [note: when adding / removing attributes or modifying array-specific location elements, you need to call specific functions, such as obj.$add (key, value) to trigger updates. This is limited by the language features of ES5.] The logic of data operation is clearer and fluent, and it is more convenient to integrate with third-party data synchronization solutions.

Component system

In large-scale applications, for the sake of division of labor, reuse and maintainability, we inevitably need to abstract the application into multiple relatively independent modules. In the more traditional development model, we would only turn a part into a component when considering reuse, but in fact, the application class UI can be seen as composed entirely of a component tree:

Therefore, components are considered as a core concept in the design of Vue.js. It can be said that every Vue.js application is developed around components.

Registering a Vue.js component is simple:

Vue.component ('my-component', {/ / template template:' {{msg}} {privateMsg}}', / / accept parameter props: {msg: String

}, / / private data, which needs to be returned in the function to prevent multiple instances from sharing an object: data: function () {return {privateMsg: 'implementaries'})

After registration, you can invoke a child component as a custom element in the parent component template:

Render the result:

Hello component!

The components of Vue.js can be understood as ViewModel classes with predefined behavior. A component can predefine many options, but the core ones are the following:

Template: the template declares the mapping between the data and the DOM that is eventually presented to the user.

Data: the initial data state of a component. For reusable components, this is usually a private state.

Accepted external parameters (props): data transfer and sharing between components through parameters. Parameters default to one-way binding (from top to bottom), but can also be explicitly declared as two-way binding.

Method (methods): changes to the data are generally carried out within the method of the component. You can bind user input events to component methods through the v-on directive.

Lifecycle hook function (lifecycle hooks): a component can trigger multiple lifecycle hook functions, such as created,attached,destroyed, and so on. In these hook functions, we can encapsulate some custom logic. Compared with the traditional MVC, it can be understood that the logic of Controller is dispersed into these hook functions.

Private resources (assets): user-defined instructions, filters, components, etc. are collectively referred to as resources in Vue.js. Because global registration of resources can easily lead to naming conflicts, a component can declare its own private resources. Private resources can only be called by this component and its subcomponents.

In addition, components within the same component tree can communicate through the built-in event API. Vue.js provides a well-defined, reused, and nested component API that allows developers to build the interface of the entire application with components like building blocks. The feasibility of this idea has also been confirmed in Facebook's open source React.

Single file component format based on build tool

The core library of Vue.js only provides basic API and does not make too many constraints on how to organize the file structure of the application. However, when building large applications, the combination of Webpack+vue-loader is recommended to make the development of components more efficient.

Webpack is an open source front-end module building tool developed by Tobias Koppers. Its basic function is to package multiple JavaScript files written in module format into one file, and supports both CommonJS and AMD formats. But what makes it unique is that it provides powerful loader API to define preprocessing logic for different file formats, so that we can use CSS, templates, and even custom file formats as JavaScript modules. Webpack can also achieve a large number of advanced functions based on loader, such as automatic block packaging and on-demand loading, automatic positioning of image resource references, decision on whether to use base64 inline according to image size, hot replacement of modules during development, etc., which can be said to be one of the most competitive solutions in the front-end construction field.

I developed the vue-loader plug-in based on Webpack's loader API, which allows us to write Vue components in a single file format like this (* .vue):

.my-component h3 {color: red;} Hello from {{msg}} / follow the CommonJS module format var otherComponent = require ('. / other-component') / / Export component definition module.exports = {data: function () {return {msg: 'vue-loader'}}, components: {' other-component': otherComponent}}

At the same time, you can use other preprocessors in the * .vue file. You only need to install the corresponding Webpack loader:

.my-component h3 color reddiv.my-component h3 Hello from {{msg}} / / compile ES2015export default {data () {return {msg: 'Hello from babies'}} using Babel

Such a component format integrates the template, style and logic of a component into the same file, which is not only convenient for development, but also convenient for reuse and maintenance. In addition, Vue.js itself supports asynchronous loading of components, and with the block packaging function of Webpack, it is extremely easy to realize asynchronous on-demand loading of components.

Other characteristics

Vue.js also has several features worth mentioning:

1. Asynchronous batch DOM updates: when a large amount of data changes, all affected watcher is pushed to a queue, and each watcher is pushed only once. This queue is executed asynchronously at the next "tick" of the process. This mechanism can avoid redundant DOM operations caused by multiple changes in the same data, ensure that all DOM write operations are executed together, and avoid layout that may be caused by DOM read-write switching.

two。 Animation system: Vue.js provides a simple but powerful animation system. When the visibility of an element changes, users can not only easily define the corresponding CSS Transition or Animation effects, but also use rich JavaScript hook functions for lower-level animation processing.

3. Extensibility: in addition to custom instructions, filters, and components, Vue.js also provides a flexible mixin mechanism that allows users to reuse common features across multiple components.

Similarities and differences with Web Components

Readers with knowledge of Web Components may wonder: what is the difference between Vue.js 's components and Web Components? Here is a brief analysis.

Web Components is a set of low-level specifications, which does not have upper-level functions such as data binding and animation system, so a more appropriate comparison object may be Polymer. Polymer is similar to Vue.js in terms of API and functionality, but its rigid dependence on Web Components makes it problematic in terms of browser support-in browsers that do not support the Web Components specification, you need to load a huge amount of polyfill, which not only has an impact on performance, but also has no perfect support for some features, such as ShadowDOM,polyfill. At the same time, the Web Components specification itself has not been finalized, and there are still some differences in specific design. By contrast, Vue.js does not have any dependencies in supported browsers (IE9+).

In addition, in an environment that supports Web Components, we can simply use the Web Components underlying API to encapsulate a Vue.js component in a real custom element, thus realizing the seamless integration of Vue.js components and other frameworks.

Thank you for reading! On the "Vue.js lightweight and efficient front-end component analysis of the example analysis" this article is shared here, I hope the above content can be of some help to you, so that you can learn more knowledge, if you think the article is good, you can share it out for more people to see it!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report