Learning Vue.js need to master the ES6 (1)

Source: Internet
Author: User

For Vue the characteristics of learning es6 , do a simple summary.

var, let and Constvar and let

es6Before, JavaScript does not have block-level scopes, so-called blocks, which are blocks of code that consist of statements inside curly braces, such as

function Fire (bool) {    if  (bool) {        var foo = "Bar";    }    Console.log (foo);} Fire (true//= Bar

Although the variable foo is if in the code block of the statement, JavaScript does not have the concept of block-level scope, so it is added to the current execution environment-that is, the function, which can be accessed within the function.

Another confusing area is the variable elevation:

function Fire (bool) {    if  (bool) {        var foo = "Bar";     Else {        console.log (foo);    }} Fire (false//= undefined

As we all know, direct access to an undefined variable will be an error:

// = = uncaught Referenceerror:nope is not defined

But in the above example, it will be returned undefined . In other words, the definition of a variable is promoted to the top of the scope, equivalent to:

function Fire (bool) {    var  foo;     if (bool) {           = "Bar";     Else {        console.log (foo);    }} Fire (false);

In JavaScript, a variable that is declared but not assigned is assigned a value undefined , so the result is output undefined .

In order to solve the above problem, the let keyword, let defined variables are introduced.

First, let the defined variables are valid only within the code block:

function Fire (bool) {    if  (bool) {        = "Bar";    }    Console.log (foo);} Fire (true//= uncaught Referenceerror:foo is not defined

Second, let there is no variable promotion for the defined variable:

function Fire (bool) {    if  (bool) {        = "Bar";     Else {        console.log (foo);    }} Fire (false//= uncaught Referenceerror:foo is not defined

Therefore, use let , the above problem completely solved, this also tells us, should be avoided as far as possible var , use let instead, unless you need to use the variable promotion.

Const

constAs with let the basic usage, the defined variables have a block-level scope, and no variable promotion occurs. The difference is that const a defined variable can only be assigned once.

For a base type, it is necessary to change its value by assignment, so the const definition is equivalent to the inability to change:

Const A = 1= 2;  // uncaught typeerror:assignment to constant variable. ++a;  // uncaught typeerror:assignment to constant variable.

For arrays and objects, values can be changed:

Const ARR  = ["A", "B", "C"];arr.push ("D"); Arr.pop ();

So when do you use it const ? In some cases where duplicate assignments are not required:

Const PROVINCES == [];

In short, use more let and const less var .

Arrow functions

In Vue, the biggest benefit of using the arrow functions is that you can point to the this Vue instance:

var New Vue ({    el:' #root ',    data:{        tasks:[]    },    mounted () {        axios.get ('/tasks ' )        . Then (function  (response) {            = response.data;        })}    );

Because the callback function this points to the global object, window we need vm to access the method of the instance, and if you use the arrow function, you can write:

New Vue ({    el:' #root ',    data:{        tasks:[]    },    mounted () {           axios.get ('/tasks ' )            this. Tasks= response.data);    });

The object of the arrow function this always points to the object where the function is defined, which is equivalent to:

var New Vue ({    el:' #root ',    data:{        tasks:[]    },    mounted () {        var  this;        Axios.get ('/tasks ')        . Then (function  (response) {            =  Response.data;}        )    });
Template string

The template string is a great convenience for the definition of the component template for Vue, and before that, you need to define a template like this:

Let template = ' <div class= ' container ' ><p>Foo</p></div> ';

If you want to write multiple lines, you can use a backslash:

Let template = '<div class= ' container ' >                    <p>Foo</p>                </div>';

Or use an array form:

Let template = [    ' <div class= ' container ' > ',    ' <p>Foo</p> ',    ' </div> '].join (');

If you want to embed a variable, you can write:

Let name = "Jack"= ' <div class= "container" ><p> ' + name + ' </p></div> ';

Using template strings, you can easily write templates in multiple lines:

Let template = '    <div class= ' container ' >        <p>Foo</p>    </div> '

Because the spaces and lines of the template string are preserved, in order not to let the first line have more line breaks, you can write:

Let template = ' <div class= ' container ' >                            <p>Foo</p>                        </div>                    '

Alternatively, use the trim() method to remove leading , trailing, and line terminators from the string.

Let template = '    <div class= ' container >        <p>Foo</p>    </div> '. Trim ();

The way a template string embeds a variable or expression is also simple:

Let name = "Jack"= '    <div class= "container" >        <p>${name} are {+ 100}</p& gt;    </div> '. Trim ();
Default parameters

es6before, JavaScript could not support default parameters like PHP, so it needed to be defined manually:

function   takediscount (price, discount) {    discount  = Discount | | 0.9;     return price * discount;} Takediscount (100);

es6Allows you to define default parameters

function takediscount (price, discount = 0.9) {    return price * discount;} Takediscount (100);

You can even pass parameters as functions:

function Getdiscount () {    return 0.9;} function takediscount (price, Discount = getdiscount ()) {    return price * discount;} Takediscount (100);
Rest parameters

Start with the function's parameter pass:

function sum (a,b,c) {    = a + B + C;     return Total ;} SUM (1, 2, 3);

In JavaScript, the function arguments are actually passed as an array, and the arguments are stored in the arguments array, so the above example is equivalent to:

function sum () {    = Arguments[0] + arguments[1] + arguments[2];     return Total ;} SUM (1, 2, 3);

But not only the arguments parameters, but also other things, so it is impossible to directly use the array function to manipulate arguments . If you want to extend the addition of any number of values, you can use loops:

function sum () {    = 0;      for (Let i = 0; i < arguments.length; i++) {        = total + arguments[i];    }     return Total ;} SUM (1, 2, 3, 4, 6);

es6The rest parameter is provided to access the superfluous variable, the above example is equivalent to:

function sum (... num)    {= 0;      for (Let i = 0; i < num.length; i++) {        = total + num[i];    }     return Total ;} SUM (1, 2, 3, 4, 6);

Can be passed as a variable:

function sum (... num)    {= 0;      for (Let i = 0; i < num.length; i++) {        = total + num[i];    }     return  = [1, 2, 3, 4, 6];sum (... nums);

In the body of a function num is simply an array of parameters, so you can use array functions reduce to achieve the same function:

function sum (... num) {    return num.reduce ((preval, curval) = {        return Preval + curval;    })} SUM (1, 2, 3, 4, 6);

...It can also be used in conjunction with other parameters by simply placing additional parameters in front:

function sum (total = 0, ... num) {    return total + num.reduce (preval, curval) = {
    return preval + curval;     = [1,2,3,4];sum (... nums);
Shorthand for an object's shorthand function

Shorthand for the function, which Vue is used in:

Vue ({   ' #root ',   Data:data,   methods: {       function() {           Vm.names.push (vm.newname);            = "";       }   }});

can be abbreviated as:

New Vue ({   ' #root ',   Data:data,   methods: {       addname () {           vm.names.push (vm.newname);            = "";       }   }});

Frequently used in components:

Vue.component (' example ', {    data () {        return  {        };}    });
Shorthand for attributes
Let data = {        "Hello, Vue"    }; var New Vue ({    ' #root ',    data:data})

Can be simply written as:

Let data = {        "Hello, Vue"    }; var New Vue ({    ' #root ',    data})

That is, you can directly write variables directly in the object, and the shorthand is more straightforward when the return value of the function is an object:

function Getperson () {    = ' Jack ';     = ten;     return {name, age};     // equivalent to    // return {    //      name:name,    //      age:age    // }}getperson ();
Deconstruction Assignment

The deconstructed assignment can be easily taken to the object's Ergodic properties:

Let person = {    "Steve",    "    Curry"    , and "man"=  Person;console.log (firstname, LastName); // equivalent to // Let firstname = person.firstname; // Let lastname = Person.lastname;

It can be used in function-pass arguments:

function greet ({firstname, LastName}) {    console.log (' Hello,${firstname}.${lastname}!  `);}; Greet ({    ' Steve ',    ' Curry '});

Learning Vue.js need to master the ES6 (1)

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.