Vue.js: Lightweight and efficient front-end Component Solution (reprint)

Source: Internet
Author: User

Summary: Vue.js provides efficient data binding and flexible component systems through a simple API. In the complex ecology of the front-end, Vue.js is fortunate to receive a certain degree of attention, currently on GitHub has 5000+ star. This article will make an in-depth introduction from all sides facing vue.js.

Vue.js is a front-end development Library of my open source in February 2014, providing efficient data binding and flexible component systems through a streamlined API. In the complex ecology of the front-end, Vue.js is fortunate to receive a certain degree of attention, currently on GitHub has 5000+ star. This article will make an in-depth introduction from all sides facing vue.js. Development intent

I also worked at Google Creative Labs at the end of 2013. At that time in the project to use a period of angular, in the exclamation of data binding brings productivity improvements, I also feel angular API design is too cumbersome, making the learning curve rather steep. Intrigued by the principle of angular data binding, I started to "build wheels" and implemented a very coarse, dependency-based collection of data-binding libraries. This is the predecessor of Vue.js. At the same time in real-world development, I found that the user interface can be described entirely in nested component trees, and that a component can correspond to the ViewModel in MVVM. So I decided to refine my data binding experiment into a truly open source project, with the core idea of a "data-driven component system".

MVVM Data Binding

The nature of MVVM is to link the view and model through data binding, so that changes to the data are automatically mapped as updates to the view. Vue.js draws on the angular's instruction mechanism in data-bound API design: Users can implement data binding through HTML attributes with special prefixes, or they can use common curly brace template interpolation, or use two-way binding on form elements:

<!--instruction--><span v-text= "msg" ></span><!--interpolation--><span>{{msg}}</span><!--two-way binding --><input v-model= "MSG" >  

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

Figure 1 Vue.js's MVVM schema

Unlike angular, Vue.js's API does not have the complexity of module, controller, scope, factory, service and other concepts, all with "ViewModel instance" as the basic unit:

<!--templates--><div id= "apps" >    {{msg}}</div>
The native object is data var = {    msg: ' hello! '} Create a ViewModel instance var vm = new Vue ({    //Select Target element    el: ' #app ',    //provide initial data    Data:data})

Render Result:

<div id= "App" >    hello!</div>  

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

Realization of data observation

The principle and angular of vue.js data observation are essentially different. Readers who understand angular may know that angular's data observations are based on a dirty check (dirty checking) mechanism. Each instruction will have a corresponding object to observe the data, called Watcher; 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 old values that were previously saved. If the result of the evaluation changes, the corresponding update is triggered, and the process is called Digest cycle. There are two problems with dirty checking:

    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 is inevitably affected and it is difficult to optimize.
    2. When data changes, the framework does not proactively detect changes and requires manual digest cycle triggering to trigger the corresponding DOM update. Angular avoids this problem by automatically triggering the digest cycle in the DOM event handler, but there are still a lot of situations that require the user to trigger manually.

The Vue.js is based on a dependency collection of observation mechanisms. In principle, it is the same as the old MVVM framework knockout. The fundamentals of dependency collection are:

    1. Transform the native data into "observable objects". An observable object can be evaluated or assigned to a value.
    2. In the evaluation process of watcher, each observable object that is valued will register the current watcher as one of its own subscribers and become a dependency of the current watcher.
    3. When a dependent observable is assigned a value, it notifies all subscriptions to its own watcher and triggers the corresponding update.
    4. The advantage of dependency collection is the ability to accurately and proactively track changes in data without two problems with the dirty checks mentioned above. However, traditional dependency collection implementations, such as knockout, often need to wrap native data to make observable objects, which need to be in the form of function calls when taking values and assignments, which are cumbersome and not intuitive to use in data manipulation, and that support for objects with complex nested structures is not ideal.

Vue.js uses the Object.defineproperty method of ES5 to transform the properties of native data objects into getter and setter directly, implements the collection and triggering of dependencies within these two functions, and perfectly supports nested object structures. For arrays, the array changes are monitored by a variable method (such as push) that wraps the array. This makes almost no difference between manipulating vue.js data and manipulating native objects [note: When adding/removing properties or modifying an array-specific location element, you need to invoke a specific function, such as obj. $add (key, value) to trigger the update. This is limited by the language characteristics of the ES5. ], the logic of data manipulation is clearer and smoother, and the integration of third-party data synchronization schemes is more convenient.

Figure 2 Vue.js data Observation and data binding implementation Diagram component system

In large-scale applications, for division of labor, reuse and maintainability, we inevitably need to abstract the application into a number of relatively independent modules. In a more traditional development model, we can only make a part of a component when we think about it, but in fact, the application-class UI is entirely considered to be all composed of the component tree:

Figure 3 UI = Component Tree

Therefore, the component is used 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 ', {    //templates template    : ' <div>{{msg}} {{privatemsg}}</div> ',    // Accept parameter    props: {        msg:string<br>        },    //private data, need to be returned in function to avoid multiple instances sharing an object    data:function () {        return {            privatemsg: ' component! '}}    })

Once registered, you can invoke a child component as a custom element in the parent component template:

<my-component msg= "Hello" ></my-component>

Render Result:

<div>hello component!</div>

Vue.js components can be understood as ViewModel classes that pre-defined the behavior. A component can be predefined for many options, but the core is the following:

    • Template: A template declares the mapping between data and the DOM that is ultimately presented to the user.
    • Initial data: The initial data state of a component. For reusable components, this is usually a private state.
    • Accepted external parameters (props): Data is passed and shared between components through parameters. The parameter defaults to one-way binding (top to bottom), but it can also be explicitly declared as a two-way binding.
    • Method (Methods): Changes to the data are generally done within the component's methods. You can bind user input events and component methods through the v-on directive.
    • Life cycle hook function (lifecycle hooks): A component triggers multiple lifecycle hook functions, such as created,attached,destroyed and so on. In these hook functions, we can encapsulate some of the custom logic. The logic that can be understood as controller is dispersed into these hook functions compared to traditional MVC.
    • Private resources (assets): vue.js The user-defined directives, filters, components, etc. collectively referred to as resources. Because globally registered resources are prone to naming conflicts, a component can declare its own private resources. A private resource can be called only by that component and its subcomponents.

In addition, components within the same component tree can communicate through the built-in event APIs. Vue.js provides sophisticated APIs for defining, reusing, and nesting components, allowing developers to use components to spell out the entire application's interface like building blocks. The feasibility of this idea is also confirmed by Facebook's open source react.

Single-file component format based on the build tool

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

Webpack is an open source front-end module build tool developed by Tobias Koppers. Its basic function is to package multiple JavaScript files in a modular format into a single file, supporting both COMMONJS and AMD formats. But what makes it unique is that it provides a powerful loader API to define preprocessing logic for different file formats, allowing us to use CSS, templates, and even custom file formats as JavaScript modules. Webpack based on loader can also achieve a large number of advanced features, such as automatic block packaging and on-demand loading, image resource reference automatic positioning, depending on the size of the image to determine whether to use the Base64 inline, the development of the module hot replacement, etc., can be said to be one of the most competitive solutions in front-end construction field.

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

<style>.my-component h2 {  color:red;} </style><template>  <div class= "my-component" >    

You can also use other preprocessor in the *.vue file, just install the corresponding Webpack loader:

<style lang= "Stylus" >.my-component h2  color red</style><template lang= "Jade" > Div.my-component  H2 Hello from {{msg}}</template><script lang= "Babel" >//using Babel compilation Es2015export Default {  data () {    return {      msg: ' Hello from babel! '}}  } </script>

Such a component format, the template, style, logic of a component into the same file, which is easy to develop, but also easy to reuse and maintenance. In addition, Vue.js natively supports asynchronous loading of components, and with Webpack's chunked packaging capabilities, it is extremely easy to implement asynchronous on-demand loading of components.

Other features

Vue.js also has several features that are worth mentioning:

    1. Asynchronous bulk Dom Update: When a large amount of data changes, all affected watcher are pushed to a queue, and each watcher only pushes the queue once. This queue executes asynchronously at the next "tick" of the process. This mechanism avoids redundant DOM operations resulting from multiple changes to the same data, and ensures that all DOM writes are executed together to avoid the layout that may result from the DOM read/write switch.
    2. Animation system: Vue.js provides a simple but powerful animation system, when the visibility of an element changes, the user can not only easily define the corresponding CSS transition or animation effect, You can also use the rich JavaScript hook function for more underlying animation.
    3. Extensibility: In addition to custom directives, filters, and components, Vue.js also provides a flexible mixin mechanism that allows users to reuse common features across multiple components.
The similarities and differences with Web Components

Readers who are aware of the Web Components may have questions about what the difference is between the Vue.js component and the Web. Here is a brief analysis.

WEB components are a set of underlying specifications that do not have the upper-level features of data binding, animation systems, etc., so a more appropriate comparison object might be polymer. Polymer is similar in terms of API and functionality to Vue.js, but its hard reliance on Web Components makes it problematic for browser support--in browsers that do not support Web components, you need to load huge polyfill, Not only does it have a performance impact, but some features, such as Shadowdom,polyfill, do not have the perfect support. At the same time, the WEB components specification itself has not been finalized, and some concrete designs still have a few differences. By contrast, Vue.js does not have any dependencies in the supported browsers (ie9+).

In addition, in a Web-enabled environment, we can easily leverage the Web components underlying API to encapsulate a vue.js component in a true custom element, enabling seamless integration of vue.js components and other frameworks.

Summarize

At the beginning of the release, Vue.js was originally focused on lightweight embedded usage scenarios. Today, Vue.js is still suitable for such scenarios. Because of its light weight (22kb min+gzip), high performance, the mobile scene also has a good fit. More importantly, the well-designed component system and the supporting building tools and plug-ins have enabled Vue.js to maintain its concise API while still being fully capable of developing complex, large-scale applications.

From the birth to the present 1.5 journey, Vue.js experienced a thorough reconstruction, multiple API design improvements, has now stabilized, testing coverage for a long time to maintain the number of 100%,github bug in single digit, and all over the world have companies/ The project applies vue.js to the production environment. In late 2015, Vue.js will release the 1.0 version, please look forward to it.

"Reference link"

Vue.js Official website: http://vuejs.org

Vue.js GitHub Warehouse: Https://github.com/yyx990803/vue

Webpack Official website: Http://webpack.github.io

Vue-loader Single-page Component example: Https://github.com/vuejs/vue-loader-example

This article is selected from the programmer electronic version August 2015 A issue, this issue more articles please check here. 2000 to date all articles catalogue please check the programmer cover show. Welcome to the electronic version of the programmer (including ipad, Android, pdf).

Welcome to join CSDN Front-end AC group 2:465,281,214 for front-end technical exchange.

You can also scan the following QR code, join the csdn front-End Large lecture group, enjoy high-content online open class, but also with the professional instructor online Exchange. (If the group is full, you can add "Rachel_qg" as a friend and indicate "attend CSDN front-end Auditorium " to apply for the group. )


Upcoming CSDN front-end lecture course:

share the topic introduction : The revolutionary innovations React brings are the most exciting changes in the front-end world over the past few years. Since contacting React, we have been convinced that React will revolutionize the development experience of client developers, including front-end, IOS and Android. In this open class, we will share the progress and future trends of the React ecosystem and community from four major directions: Target platform (targets), data processing, tools, and new challenges. It will also be an online solution to the difficulties faced by front-end developers in using the react process.

Speaker Introduction: Guo Da, CTO and co-founder of Strikingly.com, has many years of experience in front-end development. In 2010, three Facebook platform apps were developed, with more than tens of thousands of users. Founded in 2012, strikingly platform was established as the first Chinese team to enter YC incubator. Strikingly.com has rewritten most of the applications using react, and is one of the more widely used react companies in the country.

Pre-Class review: Not only for UI building: Facebook react fully parsed

This article for csdn original article, without permission not reproduced, if necessary reprint please contact market#csdn.net (#换成 @)

Vue.js: Lightweight and efficient front-end Component Solution (reprint)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.