Vue talking about front-end JS Frame vue

Source: Internet
Author: User
Tags ming script tag


Vue in recent years special attention, three years ago when Angularjs occupied the front-end JS frame market for a long time, and then react framework turned out, because it has a feature is virtual DOM, from the performance of rolling angularjs, this time, vue1.0 quietly

The advent of its elegant, lightweight also attracted a part of the user, began to receive attention, 16 Mid, VUE2.0, this time Vue no matter from the performance, or from the cost is faint over the react, fire of a mess, this time, angular

Development team also developed the angular2.0 version, and renamed to Angular, absorbing the advantages of react, vue, plus the angular itself features, but also to attract a lot of users, has now been iterated to 5.0.

Learning Vue is a skill that the front-end developer must have now.

What is the front-end JS frame doing, why use

JS Framework to help developers write JS logic code, in the development of the application of JS function is divided into the following points:

    1. Rendering data

    2. Manipulate the DOM (write some effects)

    3. Operating cookies and other storage mechanism APIs

In front-end development, how to efficiently manipulate the DOM, rendering data is a front-end engineers need to consider the problem, and when the volume of data, the flow is more chaotic, how to correctly use the data, operational data is also a problem

and the JS Framework on the above several problems have their own to the perfect solution, the development cost is reduced. High performance and high efficiency. The only drawback is the need to use a certain cost to learn.

About Vue website

Vue is a progressive JavaScript framework

"Progressive framework" and "bottom-up incremental design" are two concepts of vue development

Vue can be used in any other type of project, is less expensive, more flexible, less assertive, and can be easily integrated with other technologies in Vue's projects, and because Vue's ecosystem is so large that it can find all basic types of work

Use in Vue projects

Features: Easy to use (low cost), flexible (ecosystem perfect, suitable for any size project), high efficiency (small size, optimization, good performance)

Vue is a JavaScript framework for MVVM, but the core library of Vue is focused only on the view layer, and developers are only interested in m-v mapping.

Comparison with the Angularjs

Vue's many APIs, features are similar to ANGULARJS, in fact, because Vue in the development of the time borrowed from a lot of angularjs features, and angularjs inherent shortcomings in Vue has been resolved, that is, pupil surpasses, Vue learning

Cost is much lower than angularjs because of the low complexity

Angularjs is a strong advocate, and Vue is more flexible

Vue's data flow is unidirectional and data is more popular

The angular instruction can either manipulate the DOM or encapsulate a structure logic code, for example: AD presentation module

The instructions in Vue just manipulate the DOM and use components to separate the structure logic

Angularjs performance is inferior to Vue

Use of Vue

Vue does not support IE8, because many features of ES5 are used

Can be directly through the script tag to introduce vue.js, development version and production version, development version generally we introduced in the development of the project, when the final development completed on-line when the production version is introduced, the development version is not compressed, and there are many

And the production version is all erased.

Providing a scaffold (command-line tool) in Vue can help us quickly build a webpack-based development environment ...

Example of Vue

Each application has a root instance, and in the root instance we implement a large application through the nesting of components

That is, the component is not necessarily necessary, but the instance must be

When instantiating an instance, we can pass in one; Config item, set many property methods in configuration item can implement complex function

The properties of El can be set in the configuration, and the El attribute represents the scope of this instance

Set the Data property in the configuration to bind to the instance


Excerpt from Ruan Yi Feng Blog

MVC is divided into three layers, in fact, the M layer is the data model layer, it is a real back-end data in the front-end JS mapping model, their relationship is: The data model layer and the view layer has a mapping relationship, model changes, view display will also change, when the view generates the user

Action or feedback to Controller,controller to change the model, this time the view will be a new data rendering

This is a pure MVC pattern, but many frameworks have some changes

The front-end MVC framework, such as Angularjs,backbone:

It is found that the user can directly manipulate the controller (for example, the user changes the hash value, Conrtoller directly listens to the hash value changes after executing the logic code, then notifies the model change)

The controller can operate the view directly, if, let a certain label get into the page to get the focus, do not need model to control, so it is generally directly operated (angularJS, instruction)

View can manipulate model directly (data bidirectional binding)



The view and model cannot communicate directly, all interactions are done by presenter, and the other parts of the communication are bidirectional

The view is thin, the presenter is thicker



MVVM and MVP and similar, just view and ViewModel communication is two-way binding, view operation will automatically like ViewModel through


In Vue, you can iterate through the v-for of the data by looping the DOM, the syntax is the item in/of items, the second parameter is the index (item,index) of items, you can also loop key-value pairs, the first parameter is value, the second is key, and the third

is still an index


There are also v-on in Vue to bind events to the DOM, and in v-on: followed by the type of event to bind, some simple JavaScript expressions can be executed in the value: + +--= ...

You can set some methods in the methods, so that you can write the method name directly in the value of V-on:click, the default will be passed in the method of the event object, when the method is written by adding () can be passed, if you need event object, that

The active incoming $event

V-on bound events can be any event, v-on: can be abbreviated as @

Why listen to events in HTML?

You may notice that this kind of event monitoring violates the long tradition of separation of concerns (separation of concern). But don't worry, because all Vue.js event handling methods and expressions are tightly bound to the current view's

On ViewModel, it does not cause any maintenance difficulties. In fact, there are several benefits of using v-on:

    1. A glance at the HTML template makes it easy to locate the corresponding method in JavaScript code.
    2. Because you don't have to manually bind events in JavaScript, your ViewModel code can be very pure logic, fully decoupled from the DOM, and easier to test.
    3. When a ViewModel is destroyed, all event handlers are automatically deleted. You don't have to worry about how to clean them yourself.
Template syntax

In Vue, we use the mustache interpolation ({{}}) to render the data in the template

Use the V-once directive to control the insertion of values only once, and when the data changes, the corresponding view of the template is not updated

Use the v-html directive to parse data in HTML format

In the HTML tag attribute can not use mustache interpolation, this time to add dynamic properties to the element when using V-bind to bind the property, can be abbreviated as:

When using V-bind to bind class and inline styles, Vue does some optimizations that can be controlled using object syntax and array syntax.

To prevent an expression from blinking:

    1. V-cloak

      After adding the V-cloak property to the elements in the template, the element has this property when the Vue is not loaded, and when the Vue is loaded, the property disappears, so we can set the CSS style to hide for this property.

      <style>[v-cloak]{    visibility: hidden;}</style>
    2. V-text/v-html

      V-TEXT Specifies to replace the Textcontent property of the element within the template with the data represented by the instruction value, or to prevent flicker
      V-html can parse tags, change element innerhtml, performance is poorer than v-text

    3. V-pre

      Skips the compilation of elements and their child elements, which can be used to display mustache


This is a Vue plug-in, can be used for data interaction, support the request way: Get/post/jsonp/options ...

This plugin is officially not updated maintenance, which means try not to use

Calculate Properties, listen
有的时候我们需要在模板中使用数据a,这个时候就需要用到表达式,但是有的地方我们需要对a数据进行一些简单的处理后才能使用,那么我们就会在表达式中写一些js逻辑运算```<div id="example">{{ message.split('').reverse().join('') }}</div>```这样我们的维护就会非常困难,也不便于阅读那め我们就可以在methods里设置一个方法,在模板的表达式中使用这个方法```<p>Reversed message: "{{ reversedMessage() }}"</p>// 在组件中methods: {reversedMessage: function () {    return this.message.split('').reverse().join('')}}```但是这个时候,只要vm中有数据变化,这个变化的数据可能和我们关注的数据无关,但是vm都会重新渲染模板,这个时候表达式中的方法就会重新执行,大大的影响性能这个时候其实我们可以使用监听器里完成:在vm实例中设置watch属性,在里面通过键值对来设置一些监听,键名为数据名,值可以是一个函数,这个函数在数据改变之后才会执行,两个参数分别是性格前的值和更改后的值
    a: function (val, oldVal) {        console.log('new: %s, old: %s', val, oldVal)    }
    c: {        deep:true,        handler:function (val, oldVal) {            console.log('new: %s, old: %s', val, oldVal)        }    },
    num:{        immediate:true,        handler:function(val){            this.nums = val*2        }    }

Executes the function once.


Another data

    xm:{        get:function(){//getter 当依赖改变后设置值的时候            return this.xing+'丶'+this.ming        },        set:function(val){//setter 当自身改变后执行            this.xing = val.split('丶')[0]            this.ming = val.split('丶')[1]        }    }
Filter filters

The filter (filter) can be set in Vue to enable data formatting, double curly brace interpolation, and v-bind expressions

The vue1.0 has a default filter, but it's all removed at 2.0.

So in Vue, if you want to use a filter, you need to customize

There are two kinds of custom methods: global definition and local definition, globally defined filter can be used in any instance, component, local definition is defined in instance, component, can only be used in this instance or component

    1. Global definition

      Vue.filter (Name,handler)

      Name is the name of the filter, handler is the data format processing function, the first parameter to receive is the data to be processed, what data is returned, the result of the format is what

      In the template by | (pipe character) to use, after the filter name plus () to pass the parameter, the parameters will be in the handler function in the second and subsequent formal parameter to receive

    <p>{{msg | firstUpper(3,2)}}</p>    Vue.filter('firstUpper',function (value,num=1,num2) {        console.log(num2)        return value.substr(0,num).toUpperCase()+value.substr(num).toLowerCase()    })
    1. Local definition

      Set filters in the configuration item for the instance, component, key name, filter name, and value handler

      filters:{    firstUpper:function (value,num=1,num2) {    console.log(num2)    return value.substr(0,num).toUpperCase()+value.substr(num).toLowerCase()    }}


Conditional rendering

In Vue, you can use V-if to control the display and hiding of elements in a template, which is true to show, false to hide

V-if control is whether to render this node

When we need to control the display of a set of elements hidden, it can be wrapped with a template tag, set the instructions on the template, and so on when the VM renders this group of elements, the template will not be rendered

When there is else branch logic, you can give the element with the V-else command to control, V-else will be based on the v-if to control, the effect of the opposite of v-if, attention, must be next to

There are also v-else-if instructions to implement multi-branch logic

    <input type="text" v-model="mode">        <template  v-if="mode=='A'">        

Another area to note is that Vue renders elements as efficiently as possible, often reusing existing elements rather than starting from scratch. This does make vue faster and more efficient, but sometimes we need to get the instance to update the DOM rather than

Multiplexing, you need to add a different key attribute to the DOM, because when Vue determines exactly what to render, including which Dom can be reused, it will refer to the key value, if the DOM performance is basically consistent, consistent with the conditions of reuse, but the key value is different, still


Vue also provides the v-show instruction, using the same as V-IF, which controls the display property of the element's CSS, which controls how the element is displayed and hidden, cannot be used with the v-else, and cannot be used on the template label because the template does not

Will render, and then change its CSS properties will not render and will not take effect

V-if vs V-show

V-if is a "real" conditional rendering because it ensures that the event listeners and subcomponents within the condition block are properly destroyed and rebuilt during the switchover.
V-if is also inert: if the condition is false at the initial render, nothing is done-until the condition first becomes true, the conditional block is only started.
In contrast, V-show is much simpler – regardless of the initial conditions, elements are always rendered and simply switched based on CSS.
In general, V-IF has higher switching overhead, while V-show has higher initial rendering overhead. Therefore, if you need to switch very frequently, it is better to use v-show, and if the conditions at run time are rarely changed, use v-if better.


In Vue, we can define multiple mixin to achieve code extraction reuse, ease of maintenance, and improve the logic of the page.

Note that the Data property does not use Mixin, because logically, each instance and component should be independent

A mixin is actually a purely object, which is mounted with a pull out configuration, in one instance, after importing through the Mixins option (array), this instance has the configuration of the imported mixin

And the imported configuration will not overwrite the original, but merge together

Virtual DOM

Frequent and complex DOM operations are often the point of origin for front-end performance bottlenecks, and Vue provides a solution to the virtual DOM

The core idea of the virtual DOM is that it provides a handy tool for the complex document DOM structure and minimizes DOM manipulation. This sentence, perhaps too abstract, but basic overview of the virtual DOM design ideas

(1) Provide a convenient tool to ensure the development efficiency

(2) Ensure minimal DOM operation and ensure execution efficiency

That is, the framework/tools for virtual DOM do this:

    1. Generate a complete virtual DOM tree structure based on the existing real DOM
    2. A new full virtual DOM is regenerated when the data changes, or if the page needs to be re-rendered.
    3. Take the new virtual DOM and compare it to the old virtual Dom (using the diff algorithm). After getting the place to be updated, update the content

In this way, you can reduce the operation of real DOM and improve the performance.

Component of

Modularity is the method of separating system functions into separate functional parts, generally referred to as a single thing, such as JS, CSS

The component is based on the entire functional module division of the page, the component is an HTML, CSS, JS, image and other chain resources, these parts constitute a polymer

Pros: Code reuse for ease of maintenance

The principle of dividing components: with a large number of layout structures, or independent logic, should be divided into components

Features that the component should have: composable, reusable, testable, maintainable


In Vue, we create a subclass of Vue through Vue.extend, which is actually a component.

This means that the instances of the Vue instance and the component are different but not the same, because after all, one is the parent class and one is a subclass.

General application, will have a root instance, in the root instance is a one component

Because components are embedded in an instance or parent component, that is, components can be nested with each other, and all components must have one root instance at the outermost layer, so the components are divided into: global components and local components

Global components are available in any instance, parent component, and local components can only be used in creating their own parent components or instances

Components become global, local components through different registration methods

To create a component:


Global registration:

    var App = Vue.extend({        template:"

The component uses the template to determine its own templates, template templates must have a root node, the label must be closed

The properties of a component are mounted by using the: Data method to return an object as a property of the component, so that each component instance has a separate data property

Response principle

Because Vue is the framework of MVVM, when the data changes, the view is updated immediately, and the view layer generates an action that automatically notifies the VM to change the model, so we can implement two-way data binding, where the principle is that the instance sets data

A traversal uses Object.defineproperty to generate getter and setter for the data, and when the data changes, the setter hears it and notifies the corresponding watcher tool that the logical operation updates the view.

declarative rendering

In Vue, we can first declare the data in the Vue instance and then render it in the DOM by way of {{}}

Vue talking about front-end JS Frame vue

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