[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

Time:2020-5-22

the front

Stay out of the world to observe in the dark!!! Hello everyone, I’m Nezha the devil! Re learn and consolidate your knowledge system of vuejs. If there are any knowledge points missing, please explain them in the comments so that I can update the content knowledge system in time. Welcome to collection!

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

Talk about your understanding of MVC, MVP and MVVM?

https://github.com/webVueBlog…

Vuejs encountered at corner

  1. Why do you study vuejs
  2. Complexity of front end development
  3. Features of vuejs
  4. Installing vuejs
  5. Experience vuejs
  6. MVVM architecture: separation of data and Vue objects, MVVM in Vue

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

catalog:

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

start

  1. Interpolation syntax: mustache, v-once, v-html, v-text, v-pre, V-block.
  2. Binding attribute: v-bind introduction, v-bind foundation, v-bind syntax sugar, binding class, binding style.
  3. Calculation properties
  4. Event listening: v-on introduction, v-on foundation, v-on parameter, v-on modifier
  5. Conditions and loops: conditional rendering, v-show instructions, V-IF and v-show comparison
  6. Form binding: basic use, V-model principle, other types, value binding, modifier.

Component development:

What is componentization? Vue componentization development idea

  1. To register
  2. Global and local components
  3. Parent and child components
  4. Register component syntax sugar
  5. Separate writing of template
  6. Other properties of the component
  7. Parent to child
  8. Child to parent
  9. Access to parent-child components
  10. Non parent child component communication

Componentization advanced syntax:

  1. Slot slot: compile scope, why to use slot, basic use of slot, named slot of slot, scope slot of slot.
  2. Dynamic components
  3. Asynchronous component
  4. Component declaration cycle

Vue Cli

  1. What is webback
  2. Comparison between webpack and gulp
  3. Configuration of manual webback
  4. What is Vue cli
  5. Vue cli dependent environment
  6. Installation of Vue cli

Network encapsulation

  1. Using traditional AJAX is based on XMLHttpRequest (XHR)
  2. Using jQuery Ajax
  3. Vue-resource
  4. Using Axios

Use of Axios

  1. Understand Axios: how Axios requests
  2. Send request, send get request, send concurrent request, Axios global configuration, common configuration options.
  3. Axios instance, why to create an Axios instance, how to create an Axios instance, and the encapsulation of Axios.
  4. Interceptors for Axios: requests and responses

Related to the principle of vuejs: responsive principle, source code.

vue.js What is it?

  • Vue is a progressive framework for building user interfaces.
  • From the bottom up layer by layer application, the core library is only focusing on layers.
  • Easy to learn and integrate with third-party libraries or existing projects.

Vue basic syntax

For the basic knowledge to be mastered, write simply

vue.js install

Direct CDN introduction:

  1. For prototyping or learning

code:<script></script>

  1. For production environment

code:<script></script>

  1. NPM

code:

#Latest stable version
$ npm install vue

Vue responsive initial experience

Declarative programming:

code:

<!DOCTYPE html>
<! -- Nezha the devil -- >
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <script type="text/javascript" charset="UTF-8"></script>
        <!-- <script></script> -->
    </head>
    <body>
        <div id="app">
          {{ a }}
        </div>
        
        <script type="text/javascript">
            //Our data objects
            var data = { a: 1 };
            
            //The object is added to a Vue instance
            var vm = new Vue({
              el: "#app",
              data: data
            });
            
            // data.a = "dada"
            vm.a = "qianduan";
            data.a == vm.a;
        </script>
    </body>
</html>

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

Small case – calculator

  1. New properties:methods, which is used forVueObject.
  2. New instructions:@click, which is used to listen for the click event of an element and specify the method to execute when the click occurs.

code:

<div id="app">
    <h1>Current count {{counter}}</h1>
    <button @click="increment">+</button>
    <button @click="decrement">-</button>
</div>

<script></script>

<script>
    let app = new Vue({
        el: '#app',
        data: {
            counter: 0
        },
        methods: {
            increment(){
                this.counter++
            },
            decrement(){
                this.counter--
            },
        }
    })
</script>

MVVM in Vue

The idea of MVVM

  1. View is our DOM
  2. Model is the obj we extracted
  3. ViewModel is the Vue object instance we created

How do they work?

  1. ViewModel enables data in obj to be displayed in DOM in real time through data binding
  2. ViewModel listens for DOM events through DOM listener, and changes data in obj through operations in methods

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

  • el: Type:string | HTMLElement
  • Role: decide which Vue instance will manage after thatDOM
  • data: Type:Object | Function
  • Role: data object corresponding to Vue instance
  • methods: Type:{[key:string]:Function}
  • Role: defines methods that belong to Vue and can be called elsewhere or used in instructions.

What is the life cycle of Vue

Life cycle: the whole process from birth to death

  • releaseStable version
  • debugedition
  1. Mustache syntax is double brace
  2. Interpolation operation
  3. Binding properties
  4. Calculation properties
  5. Event judgment
  6. Loop traversal
  7. Stage cases
  8. v-model

v-onceUse of instructions

<div id="app">
 <h1>{{message}}</h1>
 <h2 v-once>{{message}}</h2>
</div>

v-once

  1. The instruction does not need to be followed by any expression
  2. This instruction means that elements and components are rendered only once, and will not change with the change of data

v-html

When the data we request from the server itself is an HTML code

  1. If directly through{{}}To output, it willHTMLThe format is parsed and the corresponding content is displayed.
  2. have access tov-htmlinstructions
  3. This command is followed by the previousstringtype
  4. WillstringOfhtmlParse and render
<h1 v-html="url"></h1>

v-textAndMustacheSimilar, it is only used to display data in the interface. Generally, it accepts onestringType.

<div id="app">
 <h2 v-text="message"></h2>
 <h2>{{message}}</h2>
</div>
<script></script>
<script>
 let vm = new Vue({
    el: '#app',
    data: {
        Message: 'hello'
    }
 })
</script>

v-preUsed to skip the compilation process of this element and its sub elements and display the originalMustacheGrammar.

<div id="app">
 <p v-pre>{{message}}</p>
</div>
<script></script>
<script>
 let app = new Vue({
  el: '#app',
  data: {
      message: 'hello'
  }
 })
</script>

v-cloakThe meaning of the Cape.

<div id="app">
 <h2 v-cloak>hello{{name}}</h2>
</div>
<script>
 setTimeout(()=>{
     let app = new Vue({
      el: '#app',
      data: {
          name: 'web'
      }
     })
 },10000)
</script>

<style>
 [v-cloak] {
     display: none;
 }
</style>

Introduction of v-bind

v-bindUsed to bind one or more property values or pass them to another componentpropsValue.

<div id="app">
 <a v-bind:href="link">vuejs</a>
 <img v-bind:src="url">
</div>

<script>
 let app = new Vue({
  el: '#app',
  data: {
      
  }
 })

v-bindGrammatical sugar

v-bindThere is a corresponding grammar sugar, that is, shorthand

<div id = "app">
    <a :href="link">vuejs</a>
    <img :src="longURL">
</div>

v-bindDynamic binding class

<style>
 .active{
     color: red;
 }
</style>

<div id="app">
 <h1 class="active">{{message}}</h2>
</div>

<script>
 const app = new Vue({
  el: '#app',
  data: {
      message: 'hello'
  }
 })
</script>

bindingclassThere are two ways:

  1. Object syntax
  2. Array syntax

Object syntax:

Usage 1: bind a class directly through {}
<h2 :class="{'active': isActive}">hello</h2>

Usage 2: pass in multiple values
<h2 :class="{'active': isActive, 'line': isLine}">hello</h2>

Usage 3:
<h2 class="title" :class="{'active': isActive}"></h2>

Usage 4:
It can be put in a method or computed
<h2 class="title" :class="classes">hello</h2>

v-bindDynamic binding class, array syntax

<div id="app">
 <h2 class="title" :class="[active, line]">{{mesg}}</h2>
 <h2 class="title" :class="getClasses()">{{mesg}}</h2>
</div>

<script>
 const app = new Vue({
     el: '#app',
     data: {
         message: 'hello',
         active: 'aaa',
         line: 'bbb',
     },
     methods: {
         getClasses: function() {
             return [this.active, this.line]
         }
     }
 })
</script>

v-bindDynamic binding style

Object syntax and array syntax.

Binding method: object syntax:

:style="{ color: currentColor, fontSize: fontSize + 'px' }"

styleFollowed by an object type, object ‘skeyyescssProperty name, object’svalueIs the specific assigned value, which can come fromdataProperties in.

Binding method: array syntax:

<div v-bind:style="[baseStyles, overStyles]"></div>

styleIt is followed by the type of an array. Multiple values can be divided.

Basic properties of calculation properties

Calculation properties, written in thecomputedIn the options:

<div id="app">
 <h2>{{firstName}}{{lastName}}</h2>
</div>

<script>
 const vm = new Vue({
  el: '#app',
  data: {
      firstName: 'web',
      lastName: 'it',
  }
 })
</script>
<div id="app">
 <h2>{{fullName}}</h2>
</div>

<script>
 const vm = new Vue({
  el: '#app',
  data: {
      firstName: 'jeskson',
      lastName: 'it',
  },
  computed: {
      fullName() {
          return this.firstName + ' ' + this.lastName
      }
  }
 })
</script>

Cache of calculated properties:

Why use computational properties?

Reason: the calculation property will be cached. If it is used multiple times, the calculation property will only be called once.

Setter and getter

Each calculated property contains a getter and a setter

<div id="app">
 <div>{{fullName}}</div>
 <div>{{firstName}}</div>
 <div>{{lastName}}</div>
</div>

<script>
 let vm = new Vue({
  el: '#app',
  data: {
      firstName: 'web',
      lastName: 'it',
  },
  computed: {
      fullName: {
          get() {
              rturn this.firstName+" "+this.lastName
          },
          set(newValue){
              const names = newValue.split(' ')
              this.firstName = names[0]
              this.lastName = names[1]
          }
      }
  }
 })
</script>
computed: {
    fullName: function() {
        return this.firstName+" "+this.lastName
    }
    
    //Generally, there is no set method for calculating the property, and the property is read-only.
    fullName: {
        get: function() {
            return this.firstName + " " + this.lastName
        }
    }
}

Use of const

Const is used. In JavaScript, the identifier decorated by const is a constant and cannot be assigned again.

In ES6 development, const is preferred, and let is used only when an identifier needs to be changed.

When using cost to define an identifier, an assignment must be made.

Constant means that the object it points to cannot be modified, but the internal properties of the object can be changed.

When will const be used?

Const can be used to ensure the security of data when the identifier we decorated will not be reassigned.

Use of const:

const a=20;
A = 10; // error: cannot be modified

Const name; // error, const decorated identifier must be assigned

Let and VaR

Block level scope:

In JS, VaR is used to declare a variable. The scope of the variable is mainly related to the definition of the function.

There is no scope for other block definitions, such as if / for, etc., which often causes some problems in development.

//Click of monitor button
var btns = document.getElementsByTagName('button');
for(var i=0; i<btns.length; i++) {
    (function(i){
        btns[i].onclick = function(){
            Alert ('clicked '+ I +')
        }
    })(i)
}
let btns = document.getElementsByTagName('button');
for(let i=0;i<btns.length;i++){
    btns[i].onclick = function(){
        Alert ('clicked '+ I +' items')
    }
}

Block level scope

Variable scope: the scope in which a variable is available.

var func;
if(true) {
    var name = 'web';
    func = function() {
        console.log(name); // web
    }
    
    func(); // web
}

// name = 'it'
func(); // web -> it
console.log(name); // web -> it

No problem caused by block level scope, block level for

var btns = document.getElementsByTagName('button');
for(var i=0; i<btns.length; i++) {
    btns[i].addEventListener('click', function(){
        console.log ('the' + I + 'button is clicked');
    })
}

Closure:

var btns = document.getElementsByTagName('button');
for(var i=0; i<btns.length;i++){
    (function(i){
        btns[i].addEventListener('click', function(){
          console.log ('button' + I + ');  
        })
    })(i)
}

Why closures can solve problems, because functions are a scope.

Enhanced writing of objects

Property initialization shorthand and method shorthand:

//Attribute shorthand
//Before ES6
let name = 'web'
let age = 12
let obj1 = {
    name: name,
    age: age,
}
console.log(obj1);
//After ES6
let obj2 = {
    name, age
}
console.log(obj2)
//Method shorthand
//Before ES6
let obj1 = {
    test: function() {
        console.log('obj1')
    }
}
obj1.test();

//After ES6
let obj2 = {
    test() {
        console.log('obj2')
    }
}
obj2.test();

V-on Foundation

v-on:click="counter++"

<div id="app">
 <h2>Hits: {{counter}}</h2>
 < button v-on: Click = "counter + +" > button click < / button >
 < button v-on: Click = "btnclick" > button click 2 < / button >
</div>

let app = new Vue({
 el: '#app',
 data: {
     counter: 0
 },
 methods: {
     btnClick(){
         this.counter++
     }
 }
})

Use of v-on modifier

<div id="app">
 <div @click="divClick">
 web
 <button @ click.stop= "Btnclick" > button < / button >
</div>

Vue provides some modifiers:

. stop call event.stopPropagation ()

. prevent call event.preventDefault ()

. native listens for native events of component root elements

. once only triggers a callback once
//Stop bubbling
<button @click.stop="doThis"></button>

//Block default behavior
<button @click.prevent="doThis"></button>

//Block default behavior,没有表达式
<form @submit.prevent></form>

//Concatenation modifier
<button @click.stop.prevent = "doThis"></button>

//Key modifier, key alias
<input @keyup.enter="onEnter">

//Key modifier, key code
<input @keyup.13="onEnter">

//Click callback wisdom to trigger once
<button @click.once="doThis"></button>

v-if,v-else-if,v-else

Easy to use:

<div id="app">
 < p V-IF = "score > = 90" > excellent</p>
 < p v-else-if = "score > = 80" > good</p>
 < p v-else-if = "score > = 60" > pass</p>
 < p v-else = "score < 60" > fail</p>
</div>

Login toggle:

<div id="app">
 <span v-if="type==='username'">
  < label > user account: < label >
  < input placeholder = "user account" >
 </span>
 <span v-else>
  < label > email address: < label >
  < input placeholder = "email address" >
 </span>
 < button @ Click = "handletoggle" > switch type < / button >
</div>

<script>
 let app = new Vue({
  el: '#app',
  data: {
      type: 'username'
  },
  methods: {
      handleToggle(){
          this.type = this.type === 'email' ? 'username' : 'email'
      }
  }
 })
</script>
<div id="app">
 <span v-if="isUser">
  < label for = "username" > user account < / label >
  < input type = "text" id = "username" placeholder = "user account" >
 </span>
 
 <span v-else>
  < label for = "email" > user email < / label >
  < input type = "text" id = "email" placeholder = "user email" >
 </span>
 < button @ Click = "isuser =! Isuser" > switch type < / button >
</div>

<script>
const app = new Vue({
 el: '#app',
 data: {
     isUser: true
 }
})
</script>

V-for traversal object

<div id="app">
 <ul>
  <li v-for="(value, key, index) in info">
   {{value}}-{{key}}-{{index}}
  </li>
 </ul>
</div>

<script>
 let app = new Vue({
  el: '#app',
  data: {
      info: {
          name: 'web',
          age: 12,
      }
  }
 })
</script>

Key property of component

When using V-for, add the previous one to the corresponding element or component:keyProperty.

Key is mainly used to update virtual DOM efficiently.

Which methods in the array are responsive

push()
Pop () removes the last element in the array
Shift() removes the first element in the array
Unshift () adds elements at the top of the array

splice()
sort()
reverse()

Shopping Cart

<div id="app">
<table>
<thead>
<tr>
<th></th>
< th > book name < / th >
< th > publication date < / th >
< th > price < / th >
< th > purchase quantity < / th >
< th > operation < / th >
</tr>
</thead>
<tbody>
<tr v-for="item in books">
<td v-for="value in item">{{value}}</td>
</tr>
</tbody>
</table>
</div>

Form binding V-model

The V-model instruction is used in Vue to realize the two-way binding of form elements and data.

<div id="app">
 <input type="text" v-model="message">
 <h2>{{message}}</h2>
</div>

The reduce function summarizes all the contents in the array.

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

JavaScript reduce() method

var numbers = [65, 44, 12, 4];
 
function getSum(total, num) {
    return total + num;
}
function myFunction(item) {
    document.getElementById("demo").innerHTML = numbers.reduce(getSum);
}

Definition and Usage

The reduce () method takes a function as an accumulator, and each value in the array (from left to right) starts to be reduced and finally evaluates to a value.

Reduce () can be used as a higher-order function for the function’s compose.

be careful:reduce()There is no callback function for an empty array.

grammar

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

The use and principle of V-model

<input type="text" :value="message" @input="message = $event.target.value">

<script>
 const app = new Vue({
  el: '#app',
  data: {
      Message: 'hello'
  },
  methods: {
      valueChange(event){
          this.message = event.target.value;
      }
  }
 })
</script>

v-modelIt’s grammar sugar, essence:

  1. v-bindBind avalueattribute
  2. v-onInstruction binding to current elementinputevent

code:

<input type="text" v-model="message">

<input type="text" v-bind:value="message" v-on:input="message = $event.target.value">

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

v-model:checkbox

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

There are two kinds of check boxes: single check box and multiple check boxes.

Single check box:

v-modelThis is the Boolean value.inputOfvalueDoes not affectv-modelValue of.

Multiple check boxes:

When there are multiple check boxes, the correspondingdataThe property in is an array.

When one of them is elected, it willinputOfvalueAdd to array.

<div id="app">
 <label for="check">
  < input type = "checkbox" V-model = "checked" id = "check" > agreement
 </label>
 < label > < input type = "checkbox" V-model = "hobbies" value = "Basketball" > basketball < / label >
 < label > < input type = "checkbox" V-model = "bubbles" value = "billiards" > billiards < / label >
</div>

v-model:select

selectThere are two situations: single choice and multiple choice

Single choice: only one value can be selected; multiple choice: multiple values can be selected.

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

v-modelcombinationselecttype

andcheckboxSame,selectThere are two situations: single choice and multiple choice.

Single choice, only one value can be selected,v-modelBound is a value. When we chooseoptionWhen one of thevalueAssign tomySelectMedium.

Select multiple values.v-modelBound is an array. When multiple values are selected, theoptionCorrespondingvalueAdd to arraymySelectsMedium.

//Select a value
<select v-model="mySelect">
 <option value="web">web</option>
 <option value="it">it</option>
</select>
<p>Your favorite {{myselect}}</p>

//Select multiple values
<select v-model="mySelects" multiple>
 <option value="web">web</option>
 <option value="it">it</option>
</select>
<p>Your favorite {{myselects}}</p>

Value binding in input

<label v-for="item in origin">
 <input type="checkbox" :value="item" v-model="hobbies">
 {{item}}
</label>

Modifier

lazyModifier:

  1. By default,v-modelThe default is ininputEvent that synchronizes the data in the input box.
  2. Once the data changes, the correspondingdataThe data in will automatically change.
  3. lazyThe modifier allows the data to be updated when it loses focus or when it returns.

numberModifier:

  1. By default, whether we enter letters or numbers in the input box, they are treated as string types.
  2. But if we want to deal with numeric types, it’s best to deal with the content directly as a number.
  3. numberThe modifier automatically converts what is entered in the input box to a numeric type.

trimModifier:

  1. If there are many spaces at the beginning and the end of the input, we usually want to remove them
  2. trimThe modifier can filter the spaces on the left and right sides of the content

Example:

<div id="app">
 <input type="text" v-model.lazy="message">
 <h2>{{message}}</h2>
</div>

What is componentization

  1. Componentization is vue.js Important thoughts in
  2. It provides an abstraction that allows us to develop individual reusable widgets to construct our applications
  3. Any application will be abstracted into a component tree

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

Basic steps for registering components:

  1. Create component builder
  2. Register components
  3. Using components

Example:

call Vue.extend () method to create a component constructor
call Vue.component () method, registering components
Using components within the scope of a Vue instance

Component example:

<div id="app">
<my-cpn></my-cpn>
</div>

<script></script>
<script>
 //Create component builder
 const myComponent = Vue.extend({
    template: `
     <div>
      <h2>Component title</h2>
      <p>Component paragraph</p>
     </div>`
 });
 
 //Register components
 Vue.component('my-cpn',myComponent);
</script>

Global and local components

  1. Vue.extend()callVue.extend()Create a component constructor.
  2. Usually when you create a component constructor, thetemplateTemplates representing our custom components.
  3. The template displays thehtmlcode.
  4. It’s written inVue2.xThe document for is almost invisible.
  5. Vue.component()It is to register the component constructor as a component and give it a component’s label name.
  6. Register the tag name of the component, the component constructor.

Example:

Component title

<div id="app">
 <my-cpn><my-cpn>
 <div>
  <my-cpn><my-cpn>
 </div>
</div>

Example:

<div id="app1">
 <my-cpn></my-cpn>
</div>
<div id="app2">
 <my-cpn></my-cpn>
</div>

<script></script>
<script>
//Create component builder
const myComponent = Vue.extend({
    template: `
    <div>
     <h2>web</h2>
    </div>
    `
})
//Register components
Vue.component('my-cpn',myComponent);
let app1 = new Vue({
 el: '#app1'
})
let app2 = new Vue({
 el: '#app2'
})
<div id="app1">
 <my-cpn></my-cpn>
</div>
< div id = "app2" > // not rendered
 <my-cpn></my-cpn>
</div>
<script></script>
<script>
//Create component builder
const myComponent = Vue.extend({
 template: `
 <div>
  <h2>web</h2>
 </div>
 `
 })
 let app1=new Vue({
  el: '#app1',
  components: {
      'my-cpn': myComponent
  }
 })
 let app2 = new Vue({
  el: '#app2'
 })
</script>

Parent and child components

Component tree

  1. There is a hierarchical relationship between components
  2. One of the most important relationships is the parent-child relationship

Example:

<div id="app">
 <parent-cpn></parent-cpn>
</div>
<script></script>
<script>
 //Create a subcomponent constructor
 const childComponent = Vue.extend({
  template: `
  < div > I am the content of sub components < / div >
  `
 })
 //Create a constructor for a parent component
 const parentComponent = Vue.extend({
  template: `
  <div>
  I am the content of the parent component
  <child-cpn></child-cpn>
  </div>
  `
  components: {
      'child-cpn': childComponent
  }
 })
 let app = new Vue({
  el: '#app',
  components: {
      'parent-cpn': parentComponent
  }
 })

Syntax sugar for registration component

Example: global components

<div id="app">
 <cpn1></cpn1>
</div>
<script>
 //Syntax sugar for global component registration
 //Register components
 Vue.component('cpn1', {
  template: `
  <div>
   <h2>web</h2>
  </div>
  `
 })
 const app = new Vue({
  el: '#app',
  data: {
      message: 'web',
  }
 })
</script>
<div id="app">
 <cpn2></cpn2>
</div>
//Register syntax sugar for local components
const app = new Vue({
 el: '#app',
 data: {
     message: 'web'
 },
 components: {
     'cpn2': {
         template: `
         <div>
          <h1>web</h1>
         </div>
         `
     }
 }
})
</script>

vueIt simplifies the way to register components and provides the syntax sugar for registration.

Writing method of component template extraction

vueTwo definitions are providedhtmlModule content:

  1. use<script>label
  2. use<template>label

Example:

<div id="app">
 <my-cpn></my-cpn>
</div>

<script type="text/x-template" id="myCpn">
 <div>
  <h2>web</h2>
 </div>
</script>

<script></script>
<script>
 let app = new Vue({
  el: '#app',
  components: {
      'my-cpn': {
          template: '#myCpn'
      }
  }
 })
</script>

templatelabel

<template id="cpn">
 <div>
  <h2>web</h2>
 </div>
</template>
//Register a global component
Vue.component('cpn', {
 template: '#cpn'
})

Can components access Vue instance data

Component is a separate functional module package, with its ownhtmlTemplates and their own datadata

Component object has onedataProperties,methodsProperty, thisdataProperty must be a function that returns an object with data stored inside it.

<div id="app">
 <my-cpn></my-cpn>
</div>

<template id="myCpn">
 <div>{{message}}</div>
</template>
<script></script>
<script>
let app = new Vue({
 el: '#app',
 components: {
     'my-cpn': {
         template: 'myCpn',
         data() {
             return{
                 message: 'web'
             }
         }
     }
 }
})

Parent child communication – props

How to communicate between parent and child components?

  1. adoptpropsPassing data to subcomponents
  2. Send message to parent component via event

propsBasic Usage

In components, usepropsTo declare the data received from the parent

propsValue of:

  1. String array, in which the string is the name at the time of passing.
  2. Object. The object can set the type of transfer, or set the default value, etc.

camelCase(hump nomenclature)propName needs to use its equivalentkebab-case(short horizontal line separated naming) naming:

Vue.component('blog-post', {
  //CamelCase in JavaScript
  props: ['postTitle'],
  template: '<h3>{{ postTitle }}</h3>'
})
<! -- kebab case in HTML -- >
<blog-post post-title="hello!"></blog-post>

Again, if you use a string template, then this limitation doesn’t exist.

propRespective name and type:

props: {
 title: String,
 likes: Number,
 isPublished: Boolean,
 commentIds: Array,
 author: Object,
 callback: Function,
 contactsPromise: Promise // or any other constructor
}
<! -- dynamically assign the value of a variable -- >
<blog-post v-bind:title="post.title"></blog-post>

<! -- dynamically assign a value to a complex expression -- >
<blog-post
  v-bind:title="post.title + ' by ' + post.author.name"
></blog-post>

<! -- even if '42' is static, we still need 'v-bind' to tell Vue -- >
<! -- this is a JavaScript expression, not a string. >
<blog-post v-bind:likes="42"></blog-post>

<! -- dynamic assignment with a variable. >
<blog-post v-bind:likes="post.likes"></blog-post>

Pass in all properties of an object

If you want to pass in all the properties of an object as prop, you can use theV-bind- bind:prop-name )

post: {
  id: 1,
  title: 'My Journey with Vue'
}

<blog-post v-bind="post"></blog-post>

<blog-post
  v-bind:id="post.id"
  v-bind:title="post.title"
></blog-post>

A simplepropsDelivery:

<div id="app">
 <child-cpn :message="message"></child-cpn>
</div>

<template id="childCpn">
 < div > display message: {{message}} < / div >
</template>

<script>
let app = new Vue({
 el: '#app',
 data: {
     message: 'hello'
 },
 components: {
     'child-cpn': {
         templte: '#childCpn',
         props: ['message']
     }
 }
})
</script>

stayVueRelationship between parent and child components in

propsPass down, event up.

Parent component passedpropsSend data to the child component, and the child component sends messages to the parent component through events.

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

propsSupported data types:

String

Number

Boolean

Array

Object

Date

Function

Symbol

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

Example:

Vue.component('my-component',{
 props: {
     //Type check of foundation
     propA: Number,
     //Multiple possible types
     propB: [String, Number],
     // propC: {
         type: String,
         required: true
     },
     //Number with default
     propD: {
         type: Number,
         default: 100
     },
     //Objects with default values
     propE: {
         type: Object,
          default: function(){
              return {message: 'web'}
          }
     },
     //Custom validation function
     propF: {
         vfunc: function(value) {
             return value > 1
         }
     }
 }
})

Son to father

code:

this.$emit('item-click',item)

propsIt is used to pass data from the parent component to the child component. Another common method is to pass data or events from the child component to the parent component.

Custom event:

  1. In the subcomponent, through$emit()To trigger the event.
  2. In the parent component, throughv-onTo listen for subcomponent events.

Custom event code:

<div id="app">
 <child-cpn @increment="changeTotal" @decrement="changeTotal"></child-cpn>
 <h2>Number of hits</h2>
</div>

<template id="childCpn">
 <div>
  <button @click="increment">+1</button>
  <button @click="decrement">-1</button>
 </div>
</template>

let app = new Vue({
 el: '#app',
 data: {
     total: 0
 },
 methods: {
     changeTotal(counter) {
         this.total = counter
     }
 },
 components: {
     'child-cpn': {
         template: '#childCpn',
         data(){
             return{
                 counter: 0
             }
         },
         methods: {
             increment(){
                 this.counter++;
                 this.$emit('increment', this.counter)
             },
             decrement(){
                 this.counter--;
                 this.$emit('decrement',this.counter)
             }
         }
     }
 }
})

Access method of parent-child components:$children

Sometimes it is necessary for the parent component to directly access the child component, the child component to directly access the parent component, or the child component to access the parent component.

  1. Parent access child, using$childrenperhaps$refs
  2. Child component access parent component, using$parent

about$childrenVisit:

  1. this.$childrenIs an array type that contains all child component objects.
  2. Through traversal, themessageStatus.

Example:

<div id="app">
 <parent-cpn></parent-cpn>
</div>

//Parent component template
<template id="parentCpn">
 <div>
  <child-cpn1></child-cpn1>
  <child-cpn2></child-cpn2>
  < button @ Click = "showchildcpn" > show all subcomponent information < / button >
 </div>
</template>

//Subcomponent
<template id="childCpn1">
 <h2>I am sub component 1</h2>
</template>
//Subcomponent
<template id="childCpn2">
 <h2>I am sub component 2</h2>
</template>

Vue.component('parent-cpn',{
 template: '#parentCpn',
 methods: {
     showChildCpn(){
         for(let i=0; i<this.$children.length; i++){
             console.log(this.$children[i].message)
         }
     }
 }
})

Access method of parent-child components:$parent

The parent component can be accessed directly in the child component through the$parent

  1. Although you can$parentVisit the parent component, but try not to
  2. The child component should try to avoid directly accessing the data of the parent component, because the coupling is too high.

Access method of parent-child components$refs

$childrenDefects of:

  1. adopt$childrenAccess sub component is an array type, and access to its sub components is through the index value.
  2. When there are too many subcomponents and one of them needs to be taken, its index value cannot be determined and may change.
  3. Get one of the specific components that you can use$refs

$refsUse of:

  1. $refsandrefInstructions are usually used together
  2. adoptrefBinding a specificid
  3. adoptthis.$refs.idYou can access the component

Example:

<child-cpn1 ref="child1"></child-cpn1>
<child-cpn2 ref="child2"></child-cpn2>
< button @ Click = "show" > access subcomponents through refs < / button >

show() {
    console.log(this.$refs.child1.message);
    console.log(this.$refs.child2.message);
}

Look at one.vueDocument project

<template>
 <div class="xxx">
  <div class="xxx"
   :class="{active: currentIndex === index}"
   @click="itemClick(index)"
   v-for="(item,index) in titles">
   <span>{{item}}</span>
   </div>
  </div>
</template>

<script>
 export default {
     name: 'xxx',
     props: {
         titles: {
             type: Array,
             default() {
                 return []
             }
         }
     },
     data: function() {
         return {
             currentIndex: 0
         }
     },
 }
</script>

<style scoped>
 .xxx {
     xxx: xxx;
 }
</style>

Three layer part:

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

Slot slot usage

vueCode inslotWhat is it? It’s called a slot,<slot>Element as the content distribution slot in the component template, after the content is passed in<slot>The element itself will be replaced.

v-slotUsage:

  1. Default slot
  2. Named slot
  3. Scope slot
  4. slotas well asslot-scopeUsage of: child component writing, parent component writing

Default slot

Subcomponent:

//Subcomponent
<template>
<div class="content">
//Default slot
<content-box class="text">
< slot > default value < / slot >
<content-box>
</div>
</template>

slotBasic use

  1. In subcomponents, use the<slot>You can open a slot for a subcomponent.
  2. What the slot inserts depends on how the parent component is used.

The subcomponent defines a slot:

  1. <slot>The content in indicates that if no other content is inserted into the component, the changed content is displayed by default.

Example:

<div id="app">
 <my-cpn></my-cpn>
 <my-cpn>
  <p>web</p>
 </my-cpn>
</div>

<template id="myCpn">
 <div>
  Who am I
 </div>
</template>
<script>
Vue.component('my-cpn',{
 template: '#myCpn'
})

let app = new Vue({
 el: '#app'
})
</script>

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

Using named slots

  1. toslotElement add anameattribute
  2. <slot name="web"></slot>

Example:

<div id="app">
 //Nothing
 <my-cpn></my-cpn>
 
 //Incoming content
 <my-cpn>
  <span slot="left">left</span>
 </my-cpn>
 
 <my-cpn>
  <span slot="left">left</span>
  
  <span slot="center">center</span>
  
  <span slot="right">right</span>
</div>

<template id="myCpn">
 <div>
  <slot name="left">1</slot>
  <slot name="center">2</slot>
  <slot name="right">3</slot>
 </div>
</template>
<script>
 Vue.component('my-cpn', {
  template: '#myCpn'
 })
 let app = new Vue({
  el: '#app'
 })
</script>

Compilation scope

VueInstance properties:

Everything in the parent component template is compiled in the parent scope, and everything in the child component template is compiled in the child scope.

The parent component replaces the label of the slot, but the content is provided by the child component.

Modular development

What is modularity? The process of splicing a group of modules into a file in the right order. A module is the encapsulation of a group of attributes and methods to achieve specific functions.

Using constructors to encapsulate objects

function web() {
    var arr = [];
    this.add = function(val) {
        arr.push(var)
    }
    this.toString = function() {
        return arr.join('')
    }
}
var a = new web();
a.add(1); // [1]
a.toString(); // "1"
a.arr // undefined

Example:

var ModuleA = (function(){
    //Define an object
    var obj = {}
    //Add variables and methods inside an object
    obj.flag = true
    obj.myFunc = function(info) {
        console.log(info)
    };
    //Return object
    return obj
}
if(ModuleA.flag) {
    console.log('web')
}

ModuleA.myFunc('webweb')

Common modular specifications:

CommonJS,AMD,CMD,ES6InModules

What is?AMDAsynchronous module definition, which is a specification for implementing modular development on the browser side, but it is not nativejsSupported, usingAMDThe third-party library functions need to be introduced in the development of specifications, namelyRequireJS

RequireJSSolved multiplejsThe file may have a dependency relationship. The dependent file needs to be loaded into the browser earlier than the dependent file;jsWhen loading, the browser will stop rendering the page. The more files are loaded, the longer the page will lose its response time.

CMDWhat is it, it is a general module definition, problem solving andAMDIt is the same, but it is different in module definition and module loading time,CMDAdditional library files need to be introduced to the third partySeaJS

JavaScript modular programming

  1. It can solve the problem of global variable pollution in the project
  2. High development efficiency, conducive to collaborative development of multiple people
  3. Single responsibility, convenient code reuse and maintenance
  4. Resolved file dependency

So what is modularity

A project is divided according to its function. In theory, each function is a module, which does not affect each other. When it is needed, it should be loaded, and try to follow the principle of high cohesion and low coupling.

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

understandCommonJS

CommonJS is an idea, essentially reusable JavaScript, which exports specific objects and provides them for other programs to use.

usemodule.exportsandexports.objTo export an object and use therequire('module')load.

The core of modularity is: import and export

Export:CommonJS

module.exports = {
    flag: true,
    test(a,b) {
        return a+b
    },
    demo(a,b) {
        return a*b
    }
}

Import:CommonJS

//Commonjs module
let {test, demo, flag} = require('moduleA');

// =>
let ma = require('moduleA');
let test = ma.test;
let demo = ma.demo;
let flag = ma.flag;

Because the website development is becoming more and more complex, and there are many JS files, there will be some problems:

  1. Variable name conflict
  2. High file dependency complexity
  3. Too many pages loaded, not conducive to maintenance

CommonJS, define module, a separatejsA file is a module. Each module has its own scope. The variables defined in the module cannot be read by other modules except for those defined asglobalObject.

Module export:exportsandmodule.exports

Module import:require

  1. staynodeEach module has its ownmoduleobject
  2. staymoduleObject with a memberexportsIt’s also an object
  3. adoptexportsObject to export the current method or variablemodule.exportsexport
  4. nodeSimplified operation,exportsbe equal tomodule.exports, equivalent tovar exports = module.exports

Import and export of ES module

export function add(num1, num2) {
    return num1 + num2
}
export function accString(param) {
    if (param == 0) {
        Return 'off'
    }else if(param == 1) {
        Return 'on'
    }
}

import {
        accString
    } from '../../utils'
const name = 'web'

export default name

export default

A module contains a function. If you don’t want to name the function, you can let the importer decide by himself:

export default function(){
    console.log('web')
}

use:

import myFunc from '../web.js'

myFunc()

export defaultMultiple modules are not allowed in the same module

importuse

exportThe instruction exports the interface provided by the module

importDirectives are used to import content from a module

import {name, age} from './web.js'

adopt*You can import all of theexportvariable

import * as web from './web.js'

console.log(web.name);

life cycle

first:new Vue(),newOneVueFor example,Observe dataData viewing,init EventsBinding event,createdimplementcreatedMethod, judge whether there iselProperty, if not,vm.$mount(el)Indicates that it is in an unmounted state. You can call this method manually to mount. Judge whether there istemplateProperty.

If anyelAttribute, judge whether there istemplateProperty.

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

Instantiation period and loading period
Lifecycle functions during creation:beforeCreateandcreatedbeforeMountandmounted

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

beforeCreateAfter instance initialization, data observationdata observerandevent/watcherEvent configuration was called before.

Renewal period

Lifecycle functions during run:beforeUpdateandupdated

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

createdCalled after the instance has been created.

The instance has completed the following configuration: data observationdata observer, operations on properties and methods,watch/eventEvent callback.

The mount phase has not yet started,$elProperty is not currently visible.

beforeMountCalled before mount begins, relatedrenderThe function is called for the first time.mountedvm.$elIt has been attached in the document. For the existingdomThe operation of the node can be performed during.beforeUpdateCalled when data is updated, occurs in virtualdmoBefore re rendering and patching.updatedWhen the hook is called, the componentdomHas been updated, so you can now execute dependent ondomOperation of.activateddeactivatedbeforeDestroydestroyed。 Before the instance is destroyed, it is called.vueAfter the instance is destroyed, it is called.

Unloading period

Lifecycle function during destruction:beforeDestroyanddestroyed

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

Instance lifecycle hook

Each Vue instance needs to go through a series of initialization processes when it is created. You need to set data listening, compile templates, and mount instances todomAnd update when data changesdomAt the same time, some functions called life cycle hooks will be run in the process.

Used to give users the opportunity to add their own code at different stages.

beforeCreate, at this timedataIt’s invisible

data() {
    return {
        a: 1
    }
},
beforeCreate() {
    // red
    console.log (this. A); // invisible
}

createdThe instance is called after it has been created. At this time, you can’t see the content of your page. The instance has finished indicating: data observationdata observer, operations on properties and methods,watch/eventEvent callback.

At this time, the mount phase has not started,$elProperty is not currently visible.

export default {
    data() {
        return {
            a: 1
        }
    },
    beforeCreate() {
        console.log(this.a);
    },
    created() {
        // red
        console.log(this.a);
        console.log(this.$el);
        //At this time, a in the data is visible, and this. $el is not visible
    }
}

beforeMountCalled before mount begins, relatedrenderThe function is called for the first time.

export default{
    data() {
        return {
            a: 1
        }
    },
    beforeCreate() {
        console.log (this. A); // invisible
    },
    created() {
        console.log(this.a);
        console.log (this. $EL); // not visible
    },
    beforeMount() {
        console.log (this. $EL); // not visible
    }
}

mounted

export default {
    data() {
        return {
            a: 1
        }
    },
    mounted() {
        console.log (this. $EL); // now $el is visible
    }
}

beforeUpdateHook,domBefore updating, call:

beforeUpdate() {
    console.log(this.a);
}

// document.getElementById("web").innerHTML

updatedHook,domAfter updating, call:

updated() {
    console.log(this.a);
}

// document.getElementById("web").innerHTML

activatedanddeactivated(assembly)

activated() {
    console.log ("component used");
},

deactivated() {
    console.log ("component disabled");
Data to Drag},

keep-aliveyesvueThe built-in component of can keep the state in memory during the component switching process to prevent repeated renderingdom

<keep-alive>When dynamic components are wrapped, inactive component instances are cached without destroying them. and<transition>be similar,<keep-alive>It’s an abstract component: it doesn’t render aDOMElement, also does not appear in the parent component chain.

When the component is in<keep-alive>Inside is switched, itsactivatedanddeactivatedThese two lifecycle hook functions will be specified accordingly.

It is used because we don’t want the components to be re rendered to affect the use experience, or performance, so as to avoid performance degradation due to multiple rendering. Cache and maintain the current state.

Scenario:

  1. Click the item on the item list page to jump to the item details, and the original information will still be displayed after returning
  2. The order list jumps to the order details, return, and so on.

keep-aliveLife cycle:

First entry:Created > mounted > activated; trigger deactivated after exiting; enter again: will triggeractivated; methods of event mounting, etc., which can only be executed oncemountedEach time a component enters, the method to execute is placed in theactivatedMedium.

app.vueParent component:

<template>
 <div>
  <button @click="myBtn"> myBtn </button>
  <keep-alive>
   <range v-if="isShow"></range>
  </keep-alive>
 </div>
</template>

<script>
 import range from './components/range.vue'
 export default {
     data() {
         return {
             a: 1,
             isShow: true
         }
     },
     methods: {
         myBtn() {
             this.isShow = !this.isShow
         }
     },
     components: {
         range
     }
 }
</script>

beforeDestroyanddestroyed

beeforeDestroyType isfunctionIn detail: before the instance is destroyed, the example is still fully available at this step.

The hook is not called during server-side rendering.

destroyedType isfunction, details:vueAfter the instance is destroyed, it is called.vueEverything indicated by the instance will be unbound, all event listeners will be removed, and all sub instances will be destroyed.

The hook is not called during server-side rendering.

beforeRouteEnterandbeforeRouteLeave

beforeRouteEnter() {
    console.log('beforeRouteEnter')
},

beforeRouteLeave() {
    console.log('beforeRouteLeave')
}

Used by Vue routing, added when routing in and routing out.

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

created() {
    console.log ('start executing the created hook function')
    //Get data data
    console.log ('get created property'+ this.value )
    //Get page elements
    console.log(this.$refs['example'])
    this.$nextTick(()=>{
        console.log ('execute this. $nexttick() function created by created')
    })
},

mounted() {
    console.log ('Start execution of mounted hook function ')
    //Get mount data
    console.log ('get mount data -' + this. $refs ['example ']. InnerText)
    this.$nextTick(()=>{
        console.log ('execute this. $nexttick() function created by mounted')
    })
},

methods: {
    //Update data
    updateDate(){
        
    },
    get(){
        this.value= 'update value attribute value in data'
        //Get page elements数据
        console.log(this.$refs['example').innerText)
        this.$nextTick(()=>{
          console.log(this.$refs['example'].innerText)  
        })
    }
}

var vm=new Vue({})Indicates starting to create aVueInstance object of,init events&liftcycleIndicates that avueEmpty instance object. At this time, there are only some default life cycle functions and default events on the object. Nothing else has been created,beforeCreateWhen a lifecycle function executes,dataandmethodsNone of the data in was initialized. staycreatedMiddle,dataandmethodsIt has been initialized. If you want to callmethodsMethod or operation indataData in can only be found increatedOperation in. thenvueStart editing the templatevueThe instructions in the code are executed, and finally a compiled final template string is generated in memory and rendered as the in memorydomAt this time, it’s only in memory, and the template is rendered, and the template is not attached to the real page.beforeMountAt the time of function execution, the template has been compiled in memory, but it has not been attached to the page.create vm.$el and replace 'el' with itThis step is to replace the compiled template in memory into the browser page.mountedAs long as it’s donemounted, which means the wholevueThe instance has been initialized. At this point, the component moves from the creation phase to the runtime phase.

beforeUpdateWhen executing, the data displayed in the page is still old, anddataThe data is up-to-date, and the page is not yet in sync with the latest data.updatedWhen the event is executed, the page anddataThe data has been kept in sync. It’s all new.virtual dom re-render and patchExecute according todataIn memory, re render a copy of the latest memorydomTree, when the latest memorydomAfter the tree is updated, the latest memorydomTree, re render to real page, complete data fromdatareachviewIt’s new.

beforeDestroyWhen the hook function executes,vueThe instance goes from running stage to destroying stage. At this time, the instance is still available, and the destruction process is not implemented.destroyedWhen the function is executed, the component has been completely destroyed and is unavailable.

Vue interview questions

Talk about youmvvmUnderstanding of

The process of two-way binding

viewview, routing – controllerController, dataModel

view->domviewModelModeldata

conventionalmvcIt means that the user operation will request the server-side route, the route will call the corresponding controller to process, the controller will get the data, return the results to the front end, and let the page render again.

mvvmFor the traditional front-end, the data will be manually rendered to the page,mvvmMode does not require the user to receive an actiondomElement, binding data toviewModelOn the layer, the data will be automatically rendered to the page, and the view change will be notifiedviewModelLayer update data.

Vue responsive principle

  1. vueHow to monitor insidemessageChanges in data
  2. When the data changes,vueHow to know who to notify and refresh the interface

Core:

  • Object.defineProperty, change of listening object property
  • Publish subscriber mode

code:

Object.keys(obj).forEach(key => {
 let value = obj[key]
 
 Object.defineProperty(obj, key, {
    set(newValue) {
        //Monitor change
        value = newValue
    },
    get() {
        return value
    }
 })
})

obj.name = 'web'

Publisher subscriber

class Dep {
    constructor() {
        this.subs = []
    }
}

class Watcher {
    constructor(name) {
        this.name = name;
    }
}

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

Object’sObject.defindePropertyIn the accessor property ingetandsetmethod

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

  • Turn data intogetterandsetter, set upwatcherAnd collect dependencies.

explain:

watcherUpdate via callback functionview;observerobservationdataData, viagetnoticedepcollectwatcherdepadoptnotify()noticewatcherData updates,watcheradoptaddDep()Collect dependencies.

Observer: used to monitor hijacking alldataProperties,dep,watcher,viewCompileanalysiselInstructions in the template.

According to the figure belowvue.js》)

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

Initialize fromdataData start, usingObserverMonitor data, add individual data attributesDep, andData, there are twogettersetter。 In itsgetterProcess add collection dependency operation insetterProcedure adds the action that the notification depends on.

When parsing instructions or givingvueInstance to set the watch option or call$watchThe correspondingwatcherAnd collect dependencies.

DataadoptObserverConverted togetter/setterTo track changes in data.

When modifying the value of an object, the correspondingsettersetterDepends on collected before notificationDepEach ofWatcher, tell them that the values have changed and that the view needs to be re rendered.

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

Data bidirectional binding principle

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

What is the principle of response

  1. Core:Object.defineProperty
  2. defaultvueWhen initializing data, thedataUse of properties inObject.definePropertyRedefine all attributes. When the page gets the corresponding attribute, it will collect the dependency. If the attribute changes, it will notify the relevant dependency to update.

initDataInitialize the user’s incomingdataData,new ObserverObserve the data,this.walk(value)Processing of objects,defineReactiveLoop object properties define reactive changes,Object.defineProperty, usingObject.definePropertyRedefine the data.

Use and useObject.definePropertyRedefine each item of data.

Object.defineProperty(obj,key,{
 enumerable: true,
 configurable: true,
 get: function reactiveGetter(){
     const value=getter?getter.call(obj):val
     if(Dep.target){
         dep.depend()
         if(childOb){
             childOb.dep.depend()
             if(Array.isArray(value)){
                 dependArray(value)
             }
         }
     }
     return value
 },
 set: function reactiveSetter(newVal) {
     const value=getter?getter.call(obj).val
     if(newVal === value || (newVal !== newVal && value !==value)){
         return
     }
     if(process.env.NODE_ENV !== 'production' && customSetter){
         customSetter()
     }
     val = newVal
     childOb = !shallow && observe(newVal)
     dep.notify()
 }
})

How to detect array changes in Vue

useFunction hijackingThe method of array is rewritten,vuetakedataThe array inRewriting of prototype chain, which points to the array prototype method defined by itself, so that when the array is calledapiIf the array contains a reference type, the reference type in the array will be notifiedMonitor again

initDataInitialize the user’s incomingdataData,new ObserverObserve the data,protoAugment(value,arrayMethods)Point the prototype method of the data to the rewritten prototype.

  • Rewrite the prototype method of array
  • observerArrayLook at each item in the array in depth

code:

if(Array.isArray(value)){
    //Judge array
    if(hasProto){
        Protoaugust (value, arraymethods) // overwrite array prototype method
    }else{
        copyAugment(value,arrayMethods,arrayKeys)
    }
    this.observeArray(value)
    //Look at each item in the array in depth
}else{
    this.walk(value) 
    //Redefining object type data
}

function protoAugment(target, src: Object){
    target.__proto__ = src
}

export const arrayMethods = Object.create(arrayProto)
const methodsToPatch=[
 'push',
 'pop',
 'shift',
 'unshift',
 'splice',
 'sort',
 'reverse'
]

methodsToPatch.forEach(function (method){
    const original = arrayProto[method]
    def(arrayMethods, method, function mutator(...args){
        const result = original.apply(this.args)
        const ob = this.__ob__
        let inserted
        switch(method) {
            case 'push':
            case 'unshift':
            inserted = args
            break
            case 'splice':
            inserted = args.slice(2)
            break
        }
        if(inserted) ob.observerArray(inserted)
        //Observe the inserted data again
        ob.dep.notify()
        //Notification view update
        return result
    }
}

observeArray(items: Array<any>) {
    for(let i=0, l = items.length; i<1; i++) {
        observe(item[i])
        //Observe each item in the array
    }
}

Why Vue uses asynchronous rendering

If asynchronous update is not adopted, the current component will be re rendered every time the data is updated for the sake of performance.

dep.notify()noticewatcherUpdate,subs[i].update()Call in turnwatcherOfupdatequeueWatchertakewatcherTo put it back in the queue,nextTick(flushSchedulerQueue)Asynchronous ClearwatcherQueues.

Nexttick implementation principle

Micro task is executed before macro task

nextTickMethod mainly uses macro task and micro task, defines an asynchronous method, and calls several timesnextTickThe method will be stored in the queue, and the current queue will be emptied through this asynchronous method.

nextTickMethod is asynchronous.

Principle:nextTick(cb)callnextTickafferentcbcallbacks.push(cb)Store the callback in the array,timerFunc()calltimerFunc, return topromisesupportpromiseThe way of writing.

webpack

What is webback? Webback is the static state of a modern JavaScript applicationmodular packing Tools.

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

Webpack is a front-end modular packaging tool

Webpack needs to be installed node.js , node.js Package management tool NPM

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

Global installation

npm install [email protected] -g

Local installation

npm install [email protected] --save-dev

webpack.config.jsFixed name file:

const path = require("path")
module.exports = {
    entry: './src/main.js',
    output: {
        patch: './dist',
        filename: ''
    },
}

package.json

{
    "name": 'meetwebpack',
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "test": "echo ..."
    },
    "author": "",
    "license": "ISC"
}

What is?loader

loaderyeswebpackA very core concept in

loaderUse process:

  1. adoptnpmInstall the requiredloader
  2. staywebpack.config.jsInmoudulesConfigure under key

package.jsonStart defined in

{
    "name": "meetwebpack",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "build": "webpack"
    },
    "author": "",
    "license": "ISC",
    "devDependencies": {
        "webpack": "^3.6.0"
    }
}

webpackIntroduction of

webpackIt can be seen as a module packer, which can analyze your project structure, find JavaScript modules and other extension languages that cannot be run directly by browsers, and package them into appropriate formats for browsers to use.

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

It can realize code conversion, file optimization, code division, module merging, automatic refreshing, code verification and automatic release.

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

Install local webback

webpack webpack-cli -D

initialization:

yarn init -y
yarn add webpack webpack-cli -D

Webpack can be configured as 0. It is a packaging tool, which can output the results (JS module) and package (supporting JS modularization)

Run the webpack command to pack

npx webpack

webpack.config.jswebpackyesnodeIt’s writtennodeHow to write:

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

let path = require('path')
console.log(path.resolve('dist');

module.exports = {
    mode: 'development',
    //Production, development
    Entry: '' // entry
    output: {
        filename: 'bundle.js',
        //Packaged file name
        path: path.resolve(__dirname, 'build'),
        //Change relative path to absolute path
    }
}

Custom,webpack.config.my.js

Use command:

npx webpack --config webpack.config.my.js

package.json:

{
    "name": 'webpack-dev-1',
    "version": "1.0.0",
    "main": "index.js",
    "license": "MIT",
    "scripts": {
      "build": "webpack --config webpack.config.my.js"  
    },
    "devDependencies": {
        "webpack": "^4.28.3",
        "webpack-cli": "^3.2.0"
    }
}

Use command:

npm run build

// npm run build -- --config webpack.config.my.js

Configuration of development server

code:

let path = require('path')
let HtmlWebpackPlugin = require('html-webpack-plugin')
console.log(path.resolve('dist');

module.exports = {
    devServer: {
      //Configuration of development server  
      port: 3000,
      //See progress bar
      progress: true,
      contentBase: "./build",
      compress: true
    },
    mode: 'development',
    //Production, development
    Entry: '' // entry
    output: {
        filename: 'bundle.js',
        //Packaged file name
        path: path.resolve(__dirname, 'build'),
        //Change relative path to absolute path
    },
    plugins: [
        //Array, all webback plug-ins
        new HtmlWebpackPlugin({
            template: './src/index.html',
            filename: 'index.html',
            minify:{
                Removeaattributequotes: true, // delete ""
                Collapsewhitespace: true, // becomes a line
               
            },
             hash: true
        })
    ],
    module: {
        //Module
        rules: [
            //Rules
            {test: /\.css$/, use: [{
                loader: 'style-loader',
                options: {
                    insertAt: 'top'
                }
            },'css-loader'] },
        ]
    }
}
output: {
    filename: 'bundle.[ hash:8 ]. JS', // display only 8 bits after packing the filename
}
{
    "name": 'webpack-dev-1',
    "version": "1.0.0",
    "main": "index.js",
    "license": "MIT",
    "scripts": {
      "build": "webpack --config webpack.config.my.js",
      "dev": "webpack-dev-server"
    },
    "devDependencies": {
        "webpack": "^4.28.3",
        "webpack-cli": "^3.2.0"
    }
}
yarn add css-loader style-loader -D

Style:

  1. style-loaderAdd exports of modules as styles todomin
  2. css-loaderanalysiscssAfter file, useimportLoad and returncsscode
  3. less-loaderLoad and translatelessfile
  4. sass-loaderLoad and translatesass/scssfile
  5. postcss-loaderusePostCSSLoad and translatecss/sssfile
  6. stylus-loaderLoad and translateStylusfile

style-loaderInstallation:

npm install style-loader --save-dev

Usage:

It is suggested thatstyle-loaderAndcss-loaderCombined use

component.js

import style from './file.css'
  1. css-loaderOnly responsible for loading CSS files
  2. style-loaderResponsible for adding styles todomin
  3. Use multipleloaderFrom right to left

code:

// webpack.config.js
module: {
    rules: [
        {
            test: /\.css$/,
            use: ['style-loader', 'css-loader']
        }
    ]
}

cssDocument processing:style-loader

installstyle-loader

npm install --save-dev style-loader

style-loaderNeed to be placed incss-loaderIn front of,webpackUsed in readingloaderIn the process, it is read from right to left.

webpack.config.jsThe configuration of is as follows:

const path = require('path')

module.exports = {
    //Entry: can be string / array / object, here we only have one entry, so write a string.
    entry: './src/main.js',
    //Exit: usually an object, which contains at least two important attributes, path and filename
    output:{
        path:  path.resolve (E) Dirname, 'dist'), // Note: path is usually an absolute path
        filename: 'bundle.js'
    },
    module: {
        rules: {
            {
                test: /\.css$/,
                use: ['style-loader','css-loader']
            }
        }
    }
}

webpackLess file processing

Installation:

npm install --save-dev less-loader less

Example:

takecss-loader,style-loader,less-loaderChain call, all styles can be applied immediately todom

// webpack.config.js
module.exports = {
    ...
    rules: [{
        test: /\.less$/,
        use: [{
            loader: 'style-loader'
        },{
            loader: 'css-loader'
        },{
            loader: 'less-loader'
        }]
    }]
}

Image file processing

css normalcode:

body {
    background: url("../img/test.jpg")
}

url-loader

npm install --save-dev url-loader

usage

url-loaderFunctions similar tofile-loader, but you can return aDataURL

import img from './image.png'

webpack.config.js

module.exports = {
    module: {
        rules: [
            {
                test: /\.(png|jpg|gif)$/,
                use: [
                    {
                        loader: 'url-loader',
                        options: {
                            limit: 8192
                        }
                    }
                ]
            }
        ]
    }
}

img, folder to package files into

name, get the original name of the picture and put it in this position

hash:8, in order to prevent the name conflict of the picture, it is still usedhash, but we only keep eight

ext, using the original extension of the picture

Babel from ES6 to Es5

If you want ES6 to Es5, you need to use thebabel

npm install --save-dev [email protected] babel-core babel-preset-es2015

to configurewebpack.config.jsFile:

{
    test: /\.m?js$/,
    use: {
        loader: 'babel-loader',
        options: {
            presets: ['es2015']
        }
    }
}

Using Vue

How towebpackIntegration in the environmentvue.js

code:

npm install vue --save
  1. runtime-onlyIn the code, there cannot be anytemplate
  2. runtime-compilerIn the code, you can havetemplateBecause ofcompilerCan be used for compilationtemplate

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

spa(simple age web application)->vue-router(front end routing)

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

.vueFile encapsulation processing

installvue-loaderandvue-template-compiler

npm install vue-loader vue-template-compiler --save-dev

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

Recognize the plugin of webpack

  1. pluginWhat is it?
  • pluginPlug in, which is usually used to extend an existing architecture.
  • webpackThe plug-in in is rightwebpackVarious extensions of existing functions.
  1. loaderandpluginThe difference between
  • loaderIt is mainly used to convert certain types of modules. It is a converter.
  • pluginIt’s a plug-in. It’s rightwebpackIts extension is an extender.
  1. pluginUse process of:
  • adoptnpmInstall the requiredplugins
  • staywebpack.config.jsInpluginsConfigure plug-ins in

webpack.config.jsDocuments for:

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

seebundle.jsFile header:

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

Details of Vue cli

What is?vue cliCommand-Line Interface, command line interface, commonly known as scaffolding,vue cliIt is an official project scaffold. usevue-cliCan be built quicklyvueDevelopment environment and correspondingwebpackto configure.

vue cliUse of

installvueScaffolding

npm install -g @vue/cli

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

Vuecli2 initialization process

code:

vue init webpack vuecli2test
  1. Create a folder based on the name, and store the contents of the project. The name will be the default project name, but it cannot contain uppercase letters, etc
  2. Project nameProject name, cannot contain uppercase
  3. Project descriptionProject description
  4. AuthorAuthor information
  5. Vue build`runtime`
  6. Install vue-router`Whether to install or not

Directory structure details

build`configyeswebpackRelevant configuration,node_modulesIt's dependentnodeRelevant modules,srcIt's where the code is written..babelrcIs the ES code related transformation configuration,.editorconfigProject text related configuration,.gitignore`gitFolder configuration ignored by warehouse,.postcssrc.jsbycssConfiguration of the relevant transformation.

.editorconfig

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

Front end Modularization:

Why use modularity and write JS code simply? Closures cause code not to be reused and realize simple modularity,esUse of modularity in:exportandimport

npm install @vue/cli -g
npm clean cache -force

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

vue cli2initialization:

vue init webpack my-project

vue cli3Initialize project:

vue create my-project

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

The use of arrow function and this

Arrow function is a way to define a function

  1. How to define a function:function
const a = function(){
    
}
  1. Defining functions in object literals
const obj = {
    b: function() {
        
    },
    b() {
        
    }
}
  1. Arrow function
Const C = (parameter list) = >{
    
}
const c = () => {
    
}

Arrow function parameters and return values

code:

const sum = (num1, num2) => {
    return num1 + num2
}

const power = (num) => {
    return num * num
}

const num = (num1,num2) => num1 + num2
const obj = {
    a() {
        setTimeout(function() {
            console.log(this); // window
        })
        setTimeout(()=>{
          console.log (this); // obj object 
        })
    }
}

route,,vue-routerBasic use,vue-routerNested routes,vue-routerParameter passing,vue-routerNavigation guard.

Routing is a term in network engineering. Routing is the activity of transmitting information from source address to destination address through Internet.

Routers provide two mechanisms: routing and forwarding. Routing is to determine the path of packets from the source to the destination. Forwarding transfers the data from the input to the appropriate output. There is a very important concept in routing called routing table. Routing table is essentially a mapping table, which determines the direction of packets.

Back end Routing: the back end handles the mapping between URLs and pages.

Front end routing and back end routing, front end rendering and back end rendering

vue-routerandkoa-routerDifferences:

vue-routerIt’s a front-end route,koa-routerIs the back-end route.

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

vue-routerFront end routing principle:

Main mode of front-end Routing:hashMode andhistorypattern.

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

The concept of routing comes from the server. In the server, routing describes the mapping relationship between URL and processing function.

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

Front and back end rendering

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

In URLhashandhtml5Ofhistory

The core of front-end routing is changeurl, but the page does not refresh as a whole. Single page, actuallyspaThe most important feature is to add a layer of front-end routing on the basis of front-end and back-end separation. The front end maintains a set of routing rules.

urlOfhash

urlOfhashIt’s the anchor#, essentially changewindow.locationOfhrefProperty. Direct assignmentlocation.hashTo changehref, but the page does not refresh.

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

html5Ofhistorypattern:pushState

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

html5Ofhistorypattern:replaceState

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

html5Ofhistorypattern:go

history.go()

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

history.back()Equivalent tohistory.go(-1)

history.forward()Equivalent tohistory.go(1)

installvue-router

npm install vue-router --save
  1. Import the routing object and callVue.use(VueRouter)
  2. Create a route instance and pass in the route mapping configuration
  3. stayVueMount the route instance created in the instance

code:

//Configure routing related information
import VueRouter from 'vue-router'
import vue from 'vue'
import Home from '../components/Home'
import About from '../components/About'

//Through Vue.use (plug-in), install plug-in
Vue.use(VueRouter)

//Configure the application relationship between routes and components
const routes = [
 {
     path: '/home',
     component: Home
 },
 {
     path: '/about',
     component: About
 }
]

//Create a vuerouter object
const router = new VueRouter({
 routes
})

//Pass the router object to the 'Vue' instance
export default router

main.js

import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false

new Vue({
 el: '#app',
 router,
 render: h => h(App)
})

usevue-routerTo

  1. Create routing component
  2. Configure route mapping: component and path mapping relationships
  3. Using routes: through<router-link>and<router-view>

code:

assemblycomponents

// home
<template>
 <div>
  <h2>I'm home</h2>
 </div>
</template>

<script>
 export default {
     name: 'Home'
 }
</script>

<style scoped>
</style>
<template>
 <div>
  <h2>I'm about</h2>
 </div>
</template>

<script>
 export default {
     name: 'Aboout'
 }
</script>

<style scoped>
</style>

App.vue

<template>
 <div id="app">
  < router link to = "/ home" > Home Page < / router link >
  < router link to = "/ about" > about < / router link >
  <router-view></router-view>
 </div>
</div>

<script>
export default {
    name: 'App'
}
</script>

<style>
</style>

main.js

import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false

new Vue({
 el: '#app',
 router,
 render: h => h(App)
})

The accidental value and modification of the route arehistorypattern

establishrouterexample

code:

router->index.js

import Vue from 'vue'
import VueRouter from 'vue-router'

//Injection plug-in
Vue.use(VueRouter)

//Define route
const routes = []

//Create router instance
const router = new VueRouter({
 routes
})

//Export router instance
export default router

main.jscode:

import Vue from 'vue'
import App from './App'
import router from './router'

new Vue({
 el: '#app',
 router,
 render: h=>h(App)
})

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

router->index.js

import Vue from 'vue'
import VueRouter from 'vue-router'

import Home from '../components/home'
import About from '../components/about'

//Injection plug-in
Vue.use(VueRouter)

//Define route
const  routes = [
 {
     path: '/home',
     component: Home
 },
 {
     path: '/about',
     component: About
 }
]

useApp.vuecode

<template>
 <div id="app">
  < router link to = "/ home" > Home Page < / router link >
  < router link to = "/ about" > about < / router link >
  <router-view></router-view>
 </div>
</template>
<script>
export default {
    name: 'App',
    components: {
        
    }
}
  1. <router-link>The label is avue-routerBuilt in component, it will be rendered as a<a>label
  2. <router-view>The label dynamically renders different components according to the current path.
  3. Other contents of the web page, such as the title or navigation at the top, or some version information at the bottom, will match<router-view>At the same level.
  4. When routing is switched, the switched is<router-view>The other contents of the attached component will not change.

Default path for routes

By default, go to the homepage of the website,<router-view>Render the content of the homepage, but the homepage component is not displayed by default, and users must click it.

How to make the path jump to the home page by default, and<router-view>To render the homepage component, you only need to configure a mapping:

const routes = [
 {
     path: '/',
     redirect: '/home'
 }
]

Configuration resolution: inroutesAnother mapping is configured in,pathThe root path is configured:/redirectIt’s redirection, that is, we redirect the root path to/homeUnder the path of.

// main.js
const router = new VueRouter({
 //Configure the application relationship between routes and components
 routes,
 mode: 'history'
})

How to change the path:

  1. urlOfhash
  2. html5Ofhistory
  3. By default, path changes useurlOfhash

usehtml5Ofhistorypattern:

//Create router instance
const router = new VueRouter({
 routes,
 mode: 'history'
})

router-link, using a property:to, which specifies the path for the jump.tagCan be specified<router-link>What components are rendered later.

replaceProperty will not stayhistoryRecords, specifyingreplaceIn this case, the back key cannot return to the previous page.

active-classProperties, when<router-link>When the corresponding route matches successfully, it will automatically set arouter-link-activeOfclass, settingsactive-classYou can change the default name.

const router = new VueRouter({
 routes,
 mode: 'history',
 linkActiveClass: 'active'
})

Route code jump

App.vuecode:

// app.vue
<template>
 <div id="app">
  < button @ Click = "linktohome" > Home Page < / button >
  < button @ Click = "linktoabout" > about < / button >
  <router-view></router-view>
 </div>
</template>

<script>
 export default {
     name: 'App',
     methods: {
         linkToHome() {
             this.$router.push('/home')
         },
         linkToAbout() {
             this.$router.push('/about')
         }
     }
 }
</script>

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

<img :src="imgURL">

< router link: to = "'/ uer /' + userid" > User < / router link >

<script>
 export default {
     name: 'User',
     computed: {
         userId() {
             return this.$route.params.userId
         }
     }
 }
</sript>

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

const Home = () => import('../components/Home')
const HomeNews = () => import('../components/HomeNews')
const HomeMessage = () => import('../components/HomeMessage')

{
    path: '/home',
    component: Home,
    children: [
        {
            path: 'news',
            component: HomeNews
        },
        {
            path: 'news',
            component: HomeMessage
        }
    ]
}
< router link to = "/ home / news" > News < / router link >
< router link to = "/ home / message" > message < / router link >

Selected by default:

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

How to pass parameters

There are two main types of pass through parameters,paramsandquery

paramsType of:

  1. Configure Routing:/router/:id
  2. Method of delivery: inpathFollowed by the corresponding value
  3. Path formed after transfer:/router/123

vue-routerPass parameter code

< router link: to = "{path: '/ profile'}" > User < / router link >

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

Uniform resource locator

Uniform resource locator, uniform resource locator, uniform resource location address, URL address, etc., web address. Like a doorplate on the Internet, it is the address of a standard resource on the Internet.

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

userClick() {
    this.$router.push('/user/' + this.userId)
}

btnClick() {
    this.$router.push({
     path: '/user',
     query: {
         name: 'web',
         age: 12,
         height: 1.2
     }
    })
}

$routeand$routerThere’s a difference

Get parameters through$routeObject, in usevue-routerIn the application of, the routing object will be injected into each component and assigned asthis.$route, and when the route is switched, the route object is updated.

<template>
 <div>
  <p> {{$route.params}} </p>
 </div>
</template>

queryType of:

  1. Configure routing format:/routerIt’s also a common configuration
  2. Transfer method, using in objectsqueryOfkeyAs a means of transmission
  3. The path formed after transmission,router?id=123,/router?id=abc

$routeand$routerThere’s a difference

const router = new VueRouter({
 routes,
 mode: 'history',
 linkActiveClass: 'active'
})

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

Vue.config.productionTip = false

Vue.prototype.test = function() {
    console.log('test')
}

Vue.prototype.name  = 'web'

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

$routeand$routerThere’s a difference

  1. $routerbyVueRouterInstance, want to navigate to differenturl, use$router.pushmethod.
  2. $routeIs currentrouterYou can get it from the jump objectname,path,query,paramsWait.

vue-routerGlobal navigation

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

Meta: metadata

router.beforeEach((to,from,next) => {
    //Jump from to
    document.title = to.matched[0].meta.title
    console.log(to);
    next()
})
//Hook after
router.afterEach((to,from) => {
  console.log();  
})

Navigation guard: navigation indicates that the route is changing.

vue-routerThe navigation guard provided is mainly used to guard navigation by jumping or canceling. There are many opportunities to be embedded in the route navigation process, global, single route exclusive, or component level.

Global guard

have access torouter.beforeEach, register a global guard:

const router = new VueRouter({..})

router.beforeEach((to,from,nex)=>{
    
})

When a navigation is triggered, the global guard is called in the order of creation. Guard is executed by asynchronous resolution, and the navigation is performed by all guardsresolveI was waiting until I finished.

  1. to:Route, the destination routing object to be entered
  2. from:Route, the route the current navigation is about to leave
  3. next:Function, be sure to call this method toresolveThis hook.

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

vue-router-keep-alive

keep-aliveandvue-router

router-viewIs a component, if directly contained inkeep-aliveIn it, all the view components matching the path will be cached.

keep-aliveyesVueA built-in component that can keep the contained components in a state or avoid re rendering.

Properties:

  1. includeString or regular expression, only matching components will be cached
  2. excludeString or regular expression, any matching components will not be cached
<keep-alive>
 <router-view>
  //All view components matched by paths will be cached
 </router-view>
<keep-alive>

PromiseUse of

es6Characteristics ofPromise, which is a solution for asynchronous programming.

Asynchronous event for timer:

setTimeout(function() {
    let data = 'web'
    console.log(content)
},1000)

new Promise((resolve, reject) => {
    setTimeout(function(){
        resolve('web')
        reject('error')
    },1000)
}).then(data=>{
    console.log(data)
}).catch(error=> {
    console.log(error)
})

PromiseThree states:

  1. pendingWait state, such as network request in progress, or timer not up to time.
  2. fulfill, satisfied status, active callbackresolveAnd callback.then()
  3. reject, reject status, callbackrejectAnd callback.catch()

Vuex details

vuexIs a dedicatedvue.jsState management mode of application development

It uses centralized storage to manage the state of all components of the application, and ensures that the state changes in a predictable way with corresponding rules.

  1. State management mode
  2. Centralized storage management

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

View components - > actions (dispatch mode) - > transitions (commit mode) - > State - > view components

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

VuexFive core concepts:

StateGettersMutationActionModule

StateSingle state tree, single data source.

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

MutationStatus update

VuexOfstoreOnly way to update, submitMutation

MutationIt consists of two parts:

  1. Event type of string
  2. A callback function whose first parameter isstate

mutationDefinition of:

mutations: {
    increment(state) {
        state.count++
    }
}

adoptmutationto update

increment: function() {
    this.$store.commit('increment')
}

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

Parameter is called yesmutationLoad ofpayload

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

VuexOfstoreInstateIt’s reactive whenstateWhen the data in changes,VueThe component updates automatically.

  1. Ahead of timestoreInitialize the required properties in
  2. tostateWhen adding new properties to objects in: Using
  • useVue.set(obj,'newObj',123)
  • Assign new objects to old objects

Mutationconstant type

// mutation-types.js
export const UPDATE_INFO = 'UPDATE_INFO'

import Vuex from 'vuex'
import Vue from 'vue'
import * as types from './mutation-types'

Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        info: {
            name: 'web',
            age: 12
        }
    },
    mutations: {
        [types.UPDATE_INFO](state, payload) {
            state.info = {...state.info, 'height': payload.height
        }
    }
})
<script>
 import {UPDATE_INFO} from './store/mutation-types';
 export default{
     name: 'App',
     components: {
         
     },
     computed: {
         info(){
             return this.$store.state.info
         }
     },
     methods: {
         updateInfo(){
             this.$store.commit(UPDATE_INFO,{height:1.00})
         }
     }
 }
</script>

Note: do notmutationAsynchronous operation in,mutationSynchronization function, in which methods must be synchronized.

actionIf there are asynchronous operations, such as network requests,

//No more asynchronous operations can be used in the mutation, no more asynchronous operations can be performed here
update(state) {
    setTimeout(()=>{
        state.info.name = 'web'
    },1000)
}

mutations: {
    //Methods
    [INCREMENT](state){
        state.counter++
    }
}
actions: {
    //Context: context, = "store
    <!--aUpdateInfo(context) {-->
    <!--    setTimeout(()=>{-->
    <!--        state.info.name = 'web'-->
    <!--    },1000)-->
    <!--}-->
}
actions: {
    aUpdateInfo(context) {
        setTimeout(()=>{
            context.commit('updateInfo')
        },1000)
    }
}

// xx.vue
updateInfo(){
    this.$store.dispatch('aUpdateInfo')
}

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

updateInfo(){
    <!--this.$store.commit('updateInfo')-->
    this.$store.dispatch('aUpdateInfo',{
        message: 'web',
        success: () => {
            console.log('web')
        }
    })
}
aUpdateInfo(context, payload) {
    return new Promise((resolve, reject) => {...})
}

Use of modules in vuex

The meaning of modules

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

getters: {
    stu(){
        
    },
    stuLength(state, getters) {
        return getters.stu.length
    }
}

Use root data:

getters: {
    fullName(state) {
        return state.name + '1'
    },
    fullName1(state, getters) {
        return getters.fullName + '2'
    },
    fullName3(state, getters, rootState) {
        return getters.fullName2+rootState.counter
    }
}

In moduleactionsPrintingconsole.log(context)

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

actionsReceive onecontextParameter object, local state passingcontext.stateExposed, root node status iscontext.rootState

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

import mutations from './mutations'
import actions from './actions'
import getters from './getters'
import moduleA from './modules/moduleA'

import Vuex from 'vuex'
import Vue from 'vue'
Vue.use(Vuex)

const state = {
    
}

const store = new Vuex.Store({
    state,
    mutations,
    actions,
    getters,
    modules: {
        a: moduleA
    }
})

export default store

Network encapsulation

Encapsulation of Axios network module

ajaxIs based onXMLHttpRequest(XHR)jQuery-AjaxCompared with traditionalajaxVery easy to use.

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

axioscharacteristic:

  • Send in browserXMLHttpRequestsrequest
  • staynode.jsSend inhttprequest
  • supportPromise API
  • Intercept requests and responses
  • Transform request and response data

axiosRequest method:

axios(config)
axios.request(config)
axios.get()
axios.delete()
axios.head()
axios.post()
axios.put()
axios.patch()

install

npm install axios --save
axios({
    //Default get
    url: '',
    method: 'get'
}).then(res=>{
    console.log(res)
})
// import request from "../utils/request.js"
import {request} from './network'

export function getHome() {
    return request({
        url: '/home/xxx'
    })
}

export function getXX(type, page) {
    return request({
        url: '/home/xx',
        params: {
            type,
            page
        }
    })
}

Concurrent requests

code:

axios.all([axios({
 url: ''
}), axios({
 url: '',
 params: {
     type: '',
     page: 1,
 }
})]).then(results => {

})

// then(axios.spread((res1,res2)=>{...}))

Global configuration

axios.defaults.baseURL=''

axios.all ..{
    url: '/home'
}

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

axios.defaults.baseURL = global.HOST;

request.js

import axios from 'axios'
export function request(config,success,failure){
    //Create Axios instance
    const instance = axios.create({
        baseURL: '',
        timeout: 5000
    })
    //Send network request
    instance(config)
    .then(res=>{
        success(res)
    })
    .catch(err=>{
        failure(err)
    })
}

main.js

import {request} from './xx/request'

request({
    url: ''
},res=>{

),err=>{
    
}

It can also be usedpromiseMethod, but it returnspromise

import axios from 'axios'
export function request(config) {
    const instance = axios.create({
        baseURL: '',
        timeout: 2000
    })
    return instance(config)
}

axiosUse of interceptors

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

//Configure request and response interception
instance.interceptors.request.use(config => {
    console.log ('request intercepting success')
    return config
},err => {
    console.log ('request intercepts in failure ')
    return err
})

instance.interceptors.response.use(response => {
    console.log ('response intercepting success')
    return response.data
},err => {
    console.log ('response intercepting failure ')
    return err
})

Package Axios

// request.js
import axios from 'axios'
cosnt service = axios.create({
 baseURL: process.env.BASE_API,
 timeout: 2000
})

service.interceptors.request.use(config=>{
 //Some processing before sending the request, data conversion, configuration of request header, token setting, loading setting, etc
 config.data=JSON.stringify(config.data);
 config.headers = {
     'Content-Type':'application/x-www-form-urlencoded'
 }
 return config
},error=>{
 Promise.reject(error)
})

//Response interceptor
service.interceptors.response.use(response => {
 return response
}, error => {
  if (error && error.response) {
    switch (error.response.status) {
      case 400:
        error.message  ='error request'
        break;
      case 401:
        error.message  ='unauthorized, please login again'
        break;
      case 403:
        error.message  ='access denied'
        break;
      case 404:
        error.message  ='request error, resource not found'
        window.location.href = "/NotFound"
        break;
      case 405:
        error.message  ='request method not allowed'
        break;
      case 408:
        error.message  ='request timeout'
        break;
      case 500:
        error.message  ='server side error'
        break;
      case 501:
        error.message  ='network not implemented'
        break;
      case 502:
        error.message  ='network error'
        break;
      case 503:
        error.message  ='service not available'
        break;
      case 504:
        error.message  ='network timeout'
        break;
      case 505:
        error.message  ='HTTP version does not support this request'
        break;
      default:
        error.message  ='connection error${ error.response.status ` `
    }
  } else {
    if (JSON.stringify(error).includes('timeout')) {
      Message.error ('server response timeout, please refresh the current page ')
    }
    error.message ('failed to connect to server')
  }
  Message.error(err.message)
  return Promise.resolve(error.response)
})
//Import file
export default service

Encapsulation requesthttp.js

import request from './request'
const http ={
    /**
     *Methods: request
     *@ param URL request address 
     *@ param params request parameters
     */
    get(url,params){
        const config = {
            methods: 'get',
            url:url
        }
        if(params){
         config.params = params
        }
        return request(config)
    },
    post(url,params){
        const config = {
            methods: 'post',
            url:url
        }
        if(params){
         config.data = params
        }
        return request(config)
    },
    put(url,params){
        const config = {
            methods: 'put',
            url:url
        }
        if(params){
         config.params = params
        }
        return request(config)
    },
    delete(url,params){
        const config = {
            methods: 'delete',
            url:url
        }
        if(params) {
         config.params = params
        }
        return request(config)
    }
}

export default http
// api.js
import http from '../utils/http'
let resquest = "/xx/request/"
//Get request
export function getListAPI(params){
    return http.get(`${resquest}/getList.json`,params)
}

// js

//Create a new Axios instance,
const service = axios.create({
  baseURL: process.env.BASE_API,
  timeout: 3 * 1000
})

project

Create project:

vue create webMall

npm run serve

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

// .editorconfig
root = true
[*]
charset = utf-8
indent_style=space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

Project inwindowDeployment

main.jscode:

import store from './store'
import FastClick from 'fastclick'
import VueLazyLoad from 'vue-lazyload'

import toast from 'components/common/toast'

Vue.config.productionTip = false
//Add event bus object
Vue.prototype.$bus = new Vue()
//Install toast plug-in
Vue.use(toast)
//Solve 300ms delay of mobile terminal
FastClick.attach(document.body)
//Using lazy loaded plug-ins
Vue.use(VueLazyLoad,{
 loading: require('./xx.png')
})

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

windowsinstallnginxlinuxDeployment,centosUpper mountingnginx

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

linux ubuntu

UbuntuIs a desktop based applicationLinuxAn operating system whose name comes from Zulu or Hausa in southern Africa“ubuntu"The word.

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

Operating system:Window10 + centos6.5 (virtual machine)

yum install nginx
systemtl start nginx.service
systemctl enable nginx.service

Upload Vue project file to ECS through xftp

Using xshell to connect to ECS

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

The host is the public IP address of the instance created on alicloud

Enter the login name and password. The login name is the login name and password entered when purchasing the server.

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs

functionnpm run buildCommand, there is a dist folder, which is the package file of the Vue project.

Nginx installation configuration

stayXshellTerminal input commandyum install nginx, enter when confirmation is required”y“enter.

After installation, enterservice nginx startstart-upnginxServices.

By commandnginx -tseenginxInstallation directory.

Enter a command at the command linecd/etc/nginxSwitch tonginxUnder directory, re-entercat nginx.confView currentnginxProfile.

Enter commandwget https://nodejs.org/dist/v10.8.0/node-v10.8.0-linux-x64.tar.xzEnter and wait for installation.

Enter commandtar xvf node-v10.8.0-linux-x64.tar.xzEnter to decompress.

Summary:

  1. When a calculated property is used multiple times, it will only be called once, because it has a cache amount
  2. Modifier:stopprevent.enter.once.nativeEtc,lazynumbertrimWait.
  3. Template classification:scripttemplate
  4. Parent child component communication: parent to child,props, son to father,$emit
  5. Project,npm installnpm run serve
  6. webStormdevelopmentvuestayPluginsInstall plug-insvue.js
  7. stay2.6.0In version,VueA new unified syntax is introduced for named slots and scope slots (that is<v-slot>Instructions). It replacedslotandslot-scopeThese two features are currently obsolete, not removed, and still in the document.
  8. v-slotUsage, divided into three categories: default slot, named slot and scope slot.

Scope slot, viaslot-scopeProperty to accept the collection of properties passed in by the subcomponent

  • Default slot

code:

//Subcomponent
<template>
  <div>
  
    <header>
      < slot > default value < / slot >
    </header>
    
  </div>
</template>

Any not wrapped inv-slotOf<template>The contents of are treated as the contents of the default slot. When the subcomponent has only default slots,<v-slot>Labels can be used directly on components

//Parent component
<template>
  <div>
  
    <child>
      Content 1
      < template > content2 < / template >
      Content 3
    </child>

    <child v-slot="web">
      Slot < br >
      Slot < br >
    </child>
    
  </div>
</template>
  • Named slot:v-slotRepeat definition the samenameOnly the last defined slot content will be loaded
//Subcomponent
<template>
  <div>
  
    <main>
      <slot name="main"></slot>
    </main>
    
    <footer>
      <slot name="footer"></slot>
    </footer>
    
  </div>
</template>
  • Scope slot:
//Subcomponent
<template>
  <div>
  
    <footer>
      <slot name="footer" :user="user" :testBtn="testBtn">
        {{user.name}}
      </slot>
    </footer>
    
  </div>
</template>

<script>

exportdefault {
    name: 'child',
    data () {
      return {
        user: {
          title: 'web',
          name: 'web'
        }
      };
    },
    methods:{
      testBtn(){
        alert('web');
      }
    }
  };
  
</script>

VueHow to call directlyComponentMethod in

<template>
  <div>
    <b-component ref="BComponent"></b-component>
  </div>
</template>
 
<script>
import BComponent from './BComponent'
 
export default {
  name: 'A',
 
  data () {
  },
 
  components: {
    BComponent
  },
 
  methods: {
    callACompoentFunction () {
      this.$refs.BComponent.sayHi()
    }
  }
}
</script>
 
<style scoped>
</style>
<template>
  <div></div>
</template>
 
<script>
 
export default {
  name: 'B',
 
  data () {
  },
 
  methods: {
    sayHi () {
      console.log('web!')
    }
  }
}
</script>
 
<style scoped>
</style>

last

Welcome to my wechat jeskson(xiaoda0423), bring you into the technology group (gold digging front-end group, dada front-end technology community ⑥) for long-term exchange and learning.

Personal website: http://www.dadaqianduan.cn/#/

[both pictures and texts, like collection! 】Re learn and consolidate your knowledge system of vuejs