day67:Vue:es6 basic syntax & Vue JS basic use &vue instruction system

catalogue

Vue foreplay: basic syntax of es6

  1. let features in ES6

    1.1. Local scope

    1.2. There is no variable promotion

    1.3. The declaration cannot be repeated

    1.4. The global variable declared by let is not subordinate to the window object, and the global variable declared by var is subordinate to the window object

  2. Constant and string formatting defined in ES6

  3.es5 scope of global and local variables

  4. Function comparison between Es5 and es6

  5. Writing method of user-defined object encapsulation function in Es5 and es6

    5.1. Method of encapsulating function in Es5 object

    5.2. The writing method of encapsulating arrow function in custom object in ES6

  6. Comparison between Es5 and es6

Vue.js quick start

  1.vue.js Library Download

  2.vue. Basic use of JS Library

  3.vue.js's M-V-VM idea

Common instructions of Vue instruction system

  1. Text instructions v-html and v-test

  2. Conditional rendering instructions v-if and v-show

  3. Operation attribute v-bind

    Display wifi password effect: bind with v-on events

  4. Event binding v-on and method attributes

    Example of commodity increase and decrease in mall

Vue foreplay: basic syntax of es6

1. let features in ES6

1.1. Local scope

If the variables defined in the code block are called outside the code block, the difference between var and let is as follows

if (1){
        var a = 'xxx';
    }
    console.log(a); // xxx

 if (1){
        let b = 'xxx';
    }
    console.log(b);// report errors

If the variable inside the function is called outside the function, neither var nor let can be called

  Calling variables inside a code block outside the code block Call variables in the function body outside the function
var sure may not
let may not may not

 

 

 

 

 

 

2. There is no variable promotion

The var command will have the phenomenon of "variable promotion", that is, the variable can be used before the declaration, and the value is undefined. This phenomenon is more or less strange. According to the general logic, the variable should be used after the declaration statement.

In order to correct this phenomenon, the let command changes the syntax behavior. The variables it declares must be used after declaration, otherwise an error will be reported

console.log(xx); //undefined
    var xx = 'oo';

console.log(xxx);  //report errors
    let xxx = 'ooo';

3. The declaration cannot be repeated

var can be declared repeatedly, while let cannot be declared repeatedly

var a = 'xx'
let a = 'oo'//report errors

4. The global variable declared by let is not subordinate to the window object, and the global variable declared by var is subordinate to the window object

A brief description of the fourth feature:

There are only two ways to declare variables in ES5: var and function.

ES6 has let, const, import, class, plus var and function of ES5. There are six ways to declare variables

You also need to understand the top-level object: the top-level object in the browser environment is window

In ES5, the properties of top-level objects are equivalent to global variables. var a = 10; window.a

In ES6, there are some changes: the global variables declared by var and function are still the attributes of the top-level object; The global variables declared by let, const and class do not belong to the attributes of the top-level object, that is, from ES6, the global variables and the attributes of the top-level object begin to be separated and decoupled, so as to prevent the declared global variables from polluting the attributes of the window object, because the window object is a top-level object, and its attributes can be used in various js programs, which is not conducive to modular development, and the window object has many own attributes, In order to prevent the pollution of the top-level variables in ES6, the global variables are also isolated in ES6.

var a = 1;
    console.info(window.a);  // 2
let b = 2;
    console.info(window.b); //undefined

2. Constant and string formatting defined in ES6

Defining constants: const

// const : Features: 1.Local scope 2.There is no variable promotion 3.Declaration 4 cannot be repeated.General declaration of immutable quantity
const PI = 3.1415926;
pi = 'xx' // Error reported, constant cannot be modified!

String formatting: ${...}

Insert the value in the back quotation mark above the tab key, ${variable name}

let bb = 'jj';
var ss = `Hello ${bb}`;
console.log(ss); // Hello jj'

3.es5 scope of global and local variables

# Global and local variables of function
'''1.local variable''': 
stay JavaScript Variables declared inside a function (using var)Is a local variable, so it can only be accessed inside the function (the scope of the variable is inside the function). As long as the function runs, the local variable will be deleted.

'''2.global variable'''
The variable declared outside the function is a global variable, which can be accessed by all scripts and functions on the web page.

# Variable life cycle:
JavaScript The lifetime of variables begins when they are declared.
Local variables are deleted after the function is run.
Global variables are deleted after the page is closed.

# Scope
First, find the variable inside the function. If it cannot be found, find the outer function and find the outermost layer step by step.

4. Function comparison between Es5 and es6

//ES5 Function writing
function add(x){
    return x
}
add(5);
//ES5 Anonymous function var add = function (x) { return x }; add(5);
//ES6 Anonymous function let add = function (x) { return x }; add(5);
//ES6 Arrow function of,Is the short form of the above method let add = (x) => { return x }; console.log(add(20));
//Easier to write, but not easy to read let add = x => x; console.log(add(5));
// When there are multiple parameters, parentheses must be added. There can only be one function return value. If there are no parameters, one must be written() let add = (x,y) => x+y;

5. Writing method of user-defined object encapsulation function in Es5 and es6

1. Method of encapsulating function in Es5 object

// es5 Method of encapsulating function in object
var name = 'Zijun';
var person1 = {
    name:'exceed',
    age:18,
    f1:function () {  // Method of placing functions in custom objects
        console.log(this);// this Points to the current object,{name: "exceed", age: 18, f1: ƒ}
        console.log(this.name)  // 'exceed'
    }
};

person1.f1();  // Using functions through custom objects

2. Writing method of encapsulating arrow function in user-defined object in ES6

// ES6 The writing method of encapsulating arrow function in user-defined object in
let username = 'Zijun'; //-- window.username
let person2 = {
    name:'exceed',
    age:18,
    //f1:function(){};
    f1: () => {  // Method of placing functions in custom objects
        console.log(this); // this It no longer points to the current object, but points to person Parent object of(Called context),At this time, the parent object is ours window Object, Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, ...}
        console.log(window);// Remember window Object, global browser object, the print result is the same as above: Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, ...}
        console.log(this.username)  // 'Zijun'
    }
};
person2.f1(); // Using functions through custom objects
person2 -- window.person2

When we use this, we want this to be a person object, not a window object, so we also have the following writing method -- > monomer mode

let person3 = {
    name:'exceed',
    age:18,
    //f1:function(){};
    //f1(){}
    f1(){  // amount to f1:function(){},It's just a shorthand,The monomer mode called object is also simple to write, vue It will be seen that this method is used
        console.log(this);// this Points to the current object,{name: "exceed", age: 18, f1: ƒ}
        console.log(this.name)  // 'exceed'
    }
};
person3.f1()

6. Comparison between Es5 and es6

1.es5 method of writing classes

function Person(name,age) {
    //Encapsulation properties
    this.name = name;  //this--Python of self
    this.age = age;
}
//Class, encapsulation method, prototype chain Person.prototype.f1 = function () { console.log(this.name);//this refer to Person object, result:'exceed' };
//Class, and write anonymous functions in the form of arrow functions Person.prototype.f2 = ()=>{ console.log(this); //Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, ...} this Point to window object };

In fact, when we use the basic syntax of js in es5, we do not inherit the class, but we can inherit it. After inheritance, can we call the method of the parent class through the object instantiated by the subclass? Of course, we can. Just know. Let's see how to write the class in es6

2. How to write classes in ES6

class Person2{
    constructor(name,age){ // The monomer mode in the object. Remember the monomer mode when the function is added above? This method is similar to python of__init__()Construction method. When writing parameters, you can also write keyword parameters constructor(name='Super 2',age=18
        
        // Encapsulation properties
        this.name = name;
        this.age = age;
    }  // Note that commas cannot be written here
    
    //Packaging method
    showname(){  
        console.log(this.name);
    }  // Cannot write comma
    showage(){
        console.log(this.age);
    }
}
let p2 = new Person2('Super 2',18);
p2.showname()  //Call method  'Super 2'

Vue.js quick start

1.vue.js Library Download

vue.js is currently the most popular tool library for front-end web development, which was released by you Yuxi in February 2014.

Several other common tool libraries: react js /angular. js

Official website:

Chinese: https://cn.vuejs.org/

English: https://vuejs.org/

Official documents: https://cn.vuejs.org/v2/guide/

vue.js currently has 1 x,2.x and 3 X version, we learn 2 Version X. 2.x to 3 X is a smooth transition, which means you used 2 X code written in 3 Version of Vue JS is no problem.

2.vue. Basic use of JS Library

Download from github: https://github.com/vuejs/vue/releases

Download address on the official website: https://cn.vuejs.org/v2/guide/installation.html

The introduction of vue is similar to jQuery. The development version of vue can be used in development JS, the product should be replaced with vue min.js.

1. The basic usage syntax of Vue

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="js/vue.min.js"></script>
    
</head>
<body>
<div id="app">
    <!-- {{ message }} Express handle vue Inside the object data The corresponding data in the attribute is output to the page -->
    <!-- Display data in double labels through{{  }}To complete -->
    <p>{{ message }}</p>
</div>
</body>
  <script>
    
        // Origin: vue.js The code starts with a Vue Object. Therefore, the data should be declared every time Vue Object start.
        let vm = new Vue({
            el:'#app',   // Set current vue Object to control the label range.
            
            // data Attribute writing method 1
            data:{  // data Is to be shown to HTML The data in the label element.
              message: 'hello world!',
            }
            
            // data Attribute writing method 2
            data:function () {
                 return {
                     'msg':'Lift your head 1!'
                 }
             }
            
            // data Attribute writing method 3
            data(){   // Monomer mode is mostly used, and there is a place to write it in the later study, so we can write it down
                  return {
                      'msg':'Lift your head 2!',
                  }
              }
            });
    
    </script>
</html>

2. Summary of the above codes

// 1. vue The use of is to be created from Vue Object start
   var vm = new Vue();
   
// 2. establish vue Object needs to pass parameters. It is a user-defined object. The user-defined object must have at least two attribute members
   var vm = new Vue({
     el:"#app",
     data: {
         Data variable:"Variable value",
         Data variable:"Variable value",
         Data variable:"Variable value",
     },
   });
  //  el:Enclosure, site delimitation and setting vue Operable html Content range, the value is css of id selector,Other selectors are OK, but they are versatile id Selector.
  // data: preservation vue.js To display in html Page data.
   
// 3. vue.js To the content periphery of the controller, you must first pass through id To set.
  <div id="app">
      <h1>{{message}}</h1>
      <p>{{message}}</p>
  </div>

3. Variables in Vue can directly perform some simple and direct js operations

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test vue</title>
</head>
<body>

<div id="app">
    <!-- vue Template syntax for, and django The syntax of the template is similar -->
    <h2>{{ msg }}</h2> <!-- Put a variable and you'll see data Property to find the corresponding value -->
    <!-- Some people say that it's OK for us to write data directly like this, but please note that our future data will be dynamically taken out from the back end, so we can't write these data. Are you right -->
    <h2>{{ 'hello beautiful girl!' }}</h2>  <!-- Put a string directly -->
    <h2>{{ num+1 }}</h2>  <!-- Four arithmetic -->
      <h2>{{ 2+1 }}</h2>  <!-- Four arithmetic -->
    <h2>{{ {'name':'chao'} }}</h2> <!-- Put a custom object directly -->
    <h2>{{ person.name }}</h2>  <!-- below data Attribute person Property name The value of the property -->
    <h2>{{ 1>2?'really':'false' }}</h2>  <!-- js Ternary operation of -->
    <h2>{{ msg2.split('').reverse().join('') }}</h2>  <!-- String inversion -->


</div>

<!-- 1.Lead bag -->
<script src="vue.js"></script>
<script>
//2.Instantiate object
    new Vue({
        el:'#app',
        data:{
            msg:'cucumber',
            person:{
                name:'exceed',
            },
            msg2:'hello Vue',
            num:10,
        }
    })

</script>
</body>
</html>

3.vue.js's M-V-VM idea

MVVM is the abbreviation of model view view model. It is an architecture mode based on front-end development.

Model refers to the data in the data attribute of vue object. The data here should be displayed in the page.

View refers to the HTML page to display the data in vue. In vue, it is also called "view template".

ViewModel refers to Vue JS is the vm object when we write code. It is Vue The core of JS is responsible for connecting View and Model to ensure the consistency of View and data. Therefore, in the previous code, the data in data is displayed, and the vm object is automatically completed in the p tag.

1. Use code to understand MVVM more clearly

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/vue.min.js"></script>
    <script>
    window.onload = function(){
        // establish vm object
        var vm = new Vue({
            el: "#app",
            data: {
                name:"Headline",
                age:16,
            },
        })
    }
    </script>
</head>
<body>
    <div id="app">
        <!-- Display data in double labels through{{  }}To complete -->
        <h1>{{name}}</h1>
        <p>{{age}}</p>
        <!-- Display the data to be used in the form input box v-model To complete the template syntax, we will learn it in detail -->
        <input type="text" v-model="name">
    </div>
</body>
</html>

In the browser, you can click console Data can be accessed directly through the data and log attributes of VMEL objects

console.log(vm.$el)     # #The range that the box VM object can control
console.log(vm.$data);  # vm Object to display in the page
console.log(vm.message);# this message namely data Data declared inside,You can also use vm.Variable names display additional data,message Just an example.

2. Summary

// 1. If you want to output data As the content of ordinary labels, the data inside needs to be used{{  }}

      // vue Object data Properties:
          data:{
            name:"Xiao Ming",
          }
      // Label element:
              <h1>{{ name }}</h1>

// 2. If you want to output data The data inside is used as the value of the form element vue.js Provided element attributes v-model

      // vue Object data Properties:
          data:{
            name:"Xiao Ming",
          }
            
      // Form elements:
      <input v-model="name">
      
use v-model hold data After the data in the form element is displayed, once the user modifies the value of the form element, the data The value of the corresponding data in the page will also change accordingly. Even if this data is used in the page, it will change.

Common instructions of Vue instruction system

Directives are special attributes prefixed with "v -". Each instruction has a fixed role in vue.

In vue, many instructions are provided, such as v-html, v-if, v-model, v-for and so on.

1. Text instructions v-html and v-test

V-text is equivalent to innerText of js code, which is equivalent to the template syntax we mentioned above. It is interpolated directly in html, and the inserted text is text. If a label is written in data, the text content is rendered through template syntax. This is not unfamiliar to us. This v-text is used to assist us in using template syntax

v-html is equivalent to innerHtml

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test vue</title>
</head>
<body>

<div id="app">
    <!-- vue Template syntax for -->
    <div>{{ msg }}</div>
    <div v-text="msg"></div>
    <div v-html="msg"></div>

</div>

<script src="vue.js"></script>
<script>

    new Vue({
        el:'#app',
        data(){
            //remember data Is a function, function return An object can be an empty object, but it must be return
            return{
                msg:'<h2>exceed</h2>', //The back end returns the tag, so we can directly v-html Rendered label effect
            }
        }
    })

</script>
</body>
</html>

When the data of the data attribute of the vm object changes, the instruction will change the content or attribute of its control in the element at the same time.

Tip: because of the historical version of vue, some instructions can be written in two ways

vue1.x Writing method             vue2.x Writing method of
// v-html         ---->   {{  }}   # vue2.x also supports v-html
// v-bind:Attribute name   ---->   :attribute
// v-on:Event name     ---->   @Event name

2. Conditional rendering instructions v-if and v-show

vue provides two instructions that can be used to determine whether to display elements, namely v-if and v-show.

1. v-if

Label element:
      <!-- vue Object eventually turns the result of the condition into a Boolean value -->
            <h1 v-if="ok">Yes</h1>
data Data:
          data:{
              ok:false    // true is displayed and false is hidden
      }

2.v-else

V-else instruction to represent the "else block" of v-if. The v-else element must follow the element with v-if or v-else-if, otherwise it will not be recognized.

Label element:
            <h1 v-if="ok">Yes</h1>
            <h1 v-else>No</h1>
data Data:
          data:{
              ok:false    // true is displayed and false is hidden
      }

3.v-else-if

In vue2 After version 1.0, v-else-if and v-else-if are added. As the name suggests, they act as "else if blocks" of v-if and can be used continuously.

Multiple v-else-if statements can appear, but v-else-if must be preceded by a v-if. It can be followed by v-else or not.

Label element:
            <h1 v-if="num===1">num The value of is 1</h1>
            <h1 v-else-if="num===2">num The value of is 2</h1>
          <h1 v-else>num The value of is{{num}}</h1>
data Data:
          data:{
              num:2
      }

4.v-show

Label element:
            <h1 v-show="ok">Hello!</h1>
data Data:
          data:{
              ok:false    // true is displayed and false is hidden
      }

Summary for v-if and v-show

// 1.v-show Not behind v-else perhaps v-else-if

// 2.v-show When hiding elements, use display:none To hide, and v-if Is directly from HTML Remove element from document[DOM In operation remove]

// 3.v-if Is a "real" conditional rendering because it ensures that the event listeners and subcomponents within the conditional block are properly destroyed and rebuilt during switching.

// 4.v-if It's also lazy: if the condition is false at the time of the initial rendering, nothing is done -- the conditional block doesn't start rendering until the condition first becomes true.

// 5.by comparison, v-show It's much simpler -- no matter what the initial conditions are, the elements are always rendered and are simply based on CSS Switch.

// 6.In general, v-if Higher switching overhead, and v-show Higher initial rendering overhead. Therefore, if you need to switch very frequently, use v-show Better; If conditions rarely change at run time, use v-if Better.

3. Operation attribute v-bind

1. Format

<Tag name :Label properties="data attribute"></Tag name>

2.v-bind usage

<a v-bind:href="url1">Baidu</a>  <!-- v-bind yes vue1.x Version writing -->
<a :href="url2">TaoBao</a> <!-- v-bind Short for, just write a colon -->

3. Display wifi password effect: bind with v-on event

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test vue</title>

</head>
<body>
    <div id="app">
        <input :type="type" v-model = "xxx">
        <button @click="f1">{{ tip }}</button>
    </div>

</body>
    <script src="vue.js"></script>
    <script>
        let vm = new Vue({
            el:'#app',
            data(){
                return{
                    tip:'Show password',
                    type:'password',
                    msg:'',
                }
            },
            methods:{
                f1(){
                    if(this.type === 'password'){
                        this.type = 'text';
                        this.tip = 'Hide password';
                    }
                    else{
                        this.type = "password";
                        this.tip = 'Show password';
                    }
                }
            }

    })


    </script>


</html>

4. Event binding v-on and method attributes

There are two ways to write event operations, @ event name and v-on: event name

<button v-on:click="num++">Button</button>   <!-- v-on yes vue1.x Version writing -->
<button @click="num+=5">Button 2</button>

summary

1. use@The event name is used to bind the event
   Syntax:
      <h1 @click="num++">{{num}}</h1>

2. The event name of the bound event, all of which are js Event name:
   @submit   --->  onsubmit
   @focus    --->  onfocus
   ....

Example of commodity increase and decrease in mall

Steps:

  1. Method of adding operation data to vue object

  2. Use instructions in tags to call methods that manipulate data

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test vue</title>
    <script src="vue.js"></script>

</head>
<body>
    <div id="app">
        <button @click="add">+1</button>
        <input type="text" v-model="num">
        <button @click="sub">-1</button>
    </div>

</body>

<script>
    let vm = new Vue({
        el:'#app',
        data:{
            num:0,
        },
        methods:{
            add(){
                this.num++
            },
            sub(){
                if(this.num>0){
                    this.num--
                }
            }
        }
    })


</script>


</html>

Posted by capella07 on Wed, 11 May 2022 11:29:29 +0300