Front end learning notes____ Vue2+Vue3

Posted by bimmer528 on Wed, 05 Jan 2022 05:30:35 +0100

preface

  • Learning video address: https://www.bilibili.com/video/BV1Zy4y1K7SH?from=search&seid=16946268743532201801
  • Learning progress: this video is suitable for students with css, html, JavaScript and front-end and back-end interaction
  • Summary of learning methods: https://editor.csdn.net/md/?articleId=116121563

Part I VUE Foundation

1, Introduction to Vue

1. What is Vue?

  • It is a set of progressive JavaScript framework with user interface

2. Vue development history

3. Characteristics of Vue

  • Features: ❶ adopt component mode to improve code reuse rate and better maintain code; ❷ explicit coding, so that the coder does not need to operate DOM directly, so as to improve the development efficiency; ❸ use virtual DOM + and excellent Diff algorithm to reuse DOM nodes as much as possible.

2, Getting to know Vue

1. Vue template syntax

1.use vue You must create one Vue example,And a configuration object is to be passed in
<head>
  <script text="text/javascript" src="../js/vue.js"></script>
</head>
<body>
  <div id="root">container</div>
</body>

<script type="text/javascript">
  Vue.config.productionTip = false;  //Prevent Vue from generating production prompts at startup

  //Create Vue instance
  const x = new Vue({
    el: '#root ', / / used to specify which container the current Vue instance serves, usually css selector string (element)
    data: {},
  })
</script>
  • Vue template syntax is divided into two categories - interpolation syntax: function: used to parse the label body content; Writing method: {{xxx}}, xxx is a js expression, which can directly read all attributes in data.
  • Vue template syntax is divided into two categories - instruction syntax: function: used to parse labels (including label attributes, label body content, binding events...); Writing method: v -????.

2. Data binding

▲ one way data binding v-bind

  • One way data binding v-bind: data can only flow from data to page, short for:.

▲ bidirectional data binding v-model

  • Bidirectional data binding v-model: the following code is wrong. v-model can only be applied to form class elements (input class elements)
<h2 v-model:x="name">How do you do</h2>
  • Note: ❶ bidirectional data binding is generally applied to form elements (such as input, select, etc.); ❷ v-model:value can be abbreviated as v-model, because v-model collects the value by default.

3. Two ways of writing el and data

▲ two ways of writing el

1.el First kind
<head>
  <script text="text/javascript" src="../js/vue.js"></script>
</head>
<body>
  <div id="root">container</div>
</body>

<script type="text/javascript">
  Vue.config.productionTip = false;  //Prevent Vue from generating production prompts at startup

  const vm = new Vue({
    el: '#root ', / the first method is directly associated with the container/
    data: {},
  })
</script>
2.el Second
<head>
  <script text="text/javascript" src="../js/vue.js"></script>
</head>
<body>
  <div id="root">container</div>

  <script type="text/javascript">
    Vue.config.productionTip = false;  //Prevent Vue from generating production prompts at startup

    const vm = new Vue({
      //el: '#root', / / directly associated with container
      data: {},
    });
    vm.$mount('#root');  / This is the second way to write mount. Meaning: the writing method is flexible. For example, you can add a timer to control the execution time/
  </script>
</body>

▲ two ways to write data

1.data First kind
<head>
  <script text="text/javascript" src="../js/vue.js"></script>
</head>
<body>
  <div id="root">container</div>
</body>

<script type="text/javascript">
  Vue.config.productionTip = false;  //Prevent Vue from generating production prompts at startup

  const vm = new Vue({
    el: '#root',
    data: {},   /data The first way to write,Object type/
  })
</script>
2.data Second
<head>
  <script text="text/javascript" src="../js/vue.js"></script>
</head>
<body>
  <div id="root">container</div>
</body>

<script type="text/javascript">
  Vue.config.productionTip = false;  //Prevent Vue from generating production prompts at startup

  const vm = new Vue({
    el: '#root',
    data: function(){  /data The second way to write,Functional formula,function Can be omitted,Components must use functional expressions/
      return: 'xxx',
    },
  })
</script>

4. MVVM model

  • MVVM model: Vue refers to this model
  • M: Model: corresponds to the data in data
  • 5: V iews: Templates
  • VM: ViewModel: Vue instance object
  • It is found that all the attributes in ❶ data finally appear on the vm; ❷ in addition, all attributes of vm and Vue prototype can be directly used in Vue template.

5. Data broker

  • Review object Defineproperty method (ES6): add a property to an object
let number = 18;
let person = {
  name: 'Zhang San',
  sex: 'male',
  //age: number,
};

//When the number changes, the age can be changed synchronously. This is the use of object Defineproperty method
Object.defineproperty(person, 'age', {
  /When someone reads person of age Property time,get function(getter function)Will be called,And the return value is age Value of/
  get:function(){  //function can be omitted
    return number;
  },
  /When someone modifies person of age Property time,set function(setter function)Will be called,And will receive the specific value of the modification/
  set(value){
    number = value
  }
})
  • Data agent in Vue: operation (read / write) of attributes in another object through one object agent. The example code is as follows:
//Simple data broker
let obj = { x:200 };
let obj2 = { y:300 };

Object.defineproperty(obj2,'x',{
  get:(){
    return obj.x;
  },
  set(value){
    obj.x = value
  }
})
  • Benefits of data broker in Vue: more convenient operation of data in data.
  • Basic principle: ❶ through object Defineproperty() adds all the properties of the data object to the vm; ❷ specify a getter/setter for each attribute added to vm; ❸ operate (read / write) the corresponding properties in data within getter/setter.

6. Event handling

▲ event handling v-on

  • Basic use of events: ❶ use v-on:xxx or @ xxx to bind events, where xxx is the event name; ❷ the event callback needs to be configured in the methods object and will eventually be on the vm; ❸ for the functions configured in methods, do not use the arrow function, otherwise this is not a vm instance; ❹ the functions configured in methods are all functions managed by Vue, and this points to vm instance or component instance objects; ❺ @ click="demo" has the same effect as @ click="demo($event)", but the latter can be passed as a parameter.

▲ event modifier

  • Event modifier in Vue: ❶ prevent block default event (common); ❷ stop to prevent event bubbling (commonly used); ❸ once event is triggered only once (common); ❹ capture uses the capture mode of events; ❺ self only has event The event is triggered only when target is the element of the current operation; ❻ the default behavior of passive events is executed immediately without waiting for the event callback to complete.

▲ keyboard event key

  • Key aliases commonly used in Vue:
Keyalias
enterenter
deleteDelete (capture delete and backspace keys)
sign outesc
Spacespace
Line feedTab (special, must be used with keydown)
Up, down, left, rightup,down,left,right
  • Note: Vue does not provide an alias key. You can use the original key value of the key to bind, but note that it should be changed to kebab case (named by a short horizontal line).
  • System modifier keys (special usage): ctrl, alt, shift, meta. ❶ used with keyup: press the modifier key, then press other keys, and then release other keys to trigger the event; ❷ use with keydown: normally trigger events; ❸ you can also use keyCode to specify specific keys (not recommended).
  • Vue.config.keyCode. User defined key name = key code: you can customize key alias.

7. Calculate the attribute computed and monitor (listen) the attribute watch

▲ calculated attribute - calculated

  • Compare interpolation expressions, methods and calculation attributes to understand the necessity of calculation attributes.
1.Name Case-Implementation of interpolation syntax
<body>
  <div id="root">
    Last name:<input type="text" v-model="fristName"><br/>
    Name:<input type="text" v-model="lastName"><br/>
    Full name:<span>{{fristName}}-{{lastName}}</span>
  </div>
</body>

<script type="text/javascript">
  Vue.config.productionTip = false;  //Prevent Vue from generating production prompts at startup

  const vm = new Vue({
    el: '#root',
    data:{
      fristName: 'Zhang',
      lastName: 'three'
    }
  })
</script>
2.Name Case-methods Method implementation
<body>
  <div id="root">
    Last name:<input type="text" v-model="fristName"><br/>
    Name:<input type="text" v-model="lastName"><br/>
    Full name:<span>{{fullName()}}</span>
  </div>
</body>

<script type="text/javascript">
  Vue.config.productionTip = false;  //Prevent Vue from generating production prompts at startup

  const vm = new Vue({
    el: '#root',
    data: {
      fristName: 'Zhang',
      lastName: 'three'
    },
    methods: {
      fullName(){
        return this.fristName + '-' + this.lastName, /Problem inefficient/
      }
    }
  })
</script>
3.Name Case-Calculation attribute implementation
<body>
  <div id="root">
    Last name:<input type="text" v-model="fristName"><br/>
    Name:<input type="text" v-model="lastName"><br/>
    Full name:<span>{{fullName}}</span>
    Full name:<span>{{fullName}}</span> /Called only once fullName Medium get(),With cache,advantage/
  </div>
</body>

<script type="text/javascript">
  Vue.config.productionTip = false;  //Prevent Vue from generating production prompts at startup

  const vm = new Vue({
    el: '#root',
    data:{
      fristName: 'Zhang',
      lastName: 'three'
    },
    computed:{  //Calculation properties
      //Complete writing
      fullName:{
        /get Function: when someone reads fullName Time,get Will be called,And the return value is fullName Value of/;
        /get When is it called? ❶First read fristName Time ❷When the dependent data changes/
        get(){ return this.fristName + '-' + this.lastName },
        /set When is it called? When fullName Called when modified./
        set(){}  //It doesn't have to be written
      }
      
      //Abbreviation. If no setter is defined, the abbreviation is as follows
      fullName(){
        return this.fristName + '-' + this.lastName
      }
    }
  })
</script>
  • Definition: the attribute to be used does not exist and must be calculated from the existing attribute.
  • Principle: the bottom layer uses object Getters and setter s provided by defineproperty ().
  • When to execute the get function ❶ it will be executed once during the first reading ❶ it will be called again when the dependent data changes.
  • Advantages: compared with the methods implementation, there is an internal caching mechanism (reuse), which is more efficient and more convenient for debugging.
  • Note: ❶ the calculation attribute finally appears on the vm instance and can be read and used directly ❶ if the calculation attribute needs to be modified, it must be written in the set function to respond to the modification, and the data relied on during calculation will be changed in the set.

▲ monitoring (listening) attribute - watch

The weather switching is realized through the above learning method
<head>
  <script text="text/javascript" src="../js/vue.js"></script>
</head>
<body>
  <div id="root">
    <h2>It's a fine day today{{info}}</h2>
    <button @click="changeWeather">Switch weather</button> /event(as click)The expression after default is vm Find properties and method execution above/
  </div>
</body>

<script type="text/javascript">
  Vue.config.productionTip = false;  //Prevent Vue from generating production prompts at startup

  //Create Vue instance
  const vm = new Vue({
    el: '#root',
    data: {
      isHot: true,
    },
    computed: {
     info(){ return this.isHot ? 'scorching hot' : 'pleasantly cool' }
    },
    methods: {
      changeWeather(){ this.ihHot = ! this.isHot }
    }
  })
</script>
Understand monitoring through this case watch method
<head>
  <script text="text/javascript" src="../js/vue.js"></script>
</head>
<body>
  <div id="root">
    <h2>It's a fine day today{{info}}</h2>
    <button @click="changeWeather">Switch weather</button> 
  </div>
</body>

<script type="text/javascript">
  Vue.config.productionTip = false;  //Prevent Vue from generating production prompts at startup

  //Create Vue instance
  const vm = new Vue({
    el: '#root',
    data: {
      isHot: true,
    },
    computed: {
     info(){ return this.isHot ? 'scorching hot' : 'pleasantly cool' }
    },
    methods: {
      changeWeather(){ this.ihHot = ! this.isHot }
    }
    watch:{  /First monitoring watch method/
      isHot:{  /here isHot Is a configuration object,It is also the object of monitoring/
        immediate:true,  /Let on initialization handler Call it/
        //When does the handler call? Called when isHot changes
        handler(newValue,oldValue){ console.log(newValue,oldValue) }  /handler It is also a configuration object/
      }
    }

    /Abbreviation,When setting is not required immediate And deep Time,The first can be abbreviated like this/
    watch{
      isHot(newValue,oldValue){ console.log(newValue,oldValue) }
    }
  })

  vm.$watch('isHot', {  /Second monitoring watch method/
    immediate:true,
    handler(newValue,oldValue){ console.log(newValue,oldValue) }
  });

  /Abbreviation,When setting is not required immediate And deep Time,The second can be abbreviated like this/
    vm.$watch('isHot', function(newValue,oldValue){ console.log(newValue,oldValue) });
</script>
  • Monitoring attribute watch: when the monitored attribute changes, the callback function will be called automatically to carry out relevant operations. The monitoring attribute must exist before monitoring can be carried out.
  • There are two ways to write monitoring: ❶ when new Vue, the watch configuration is passed in ❶ through VM$ Watch monitoring.

▲ depth monitoring (listening)

Understand deep monitoring through this case-Only detect a Change of
<head>
  <script text="text/javascript" src="../js/vue.js"></script>
</head>
<body>
  <div id="root">
    <h3>a The value of is:{{number.a}}</h3>
    <button @click="number.a++">Let me a+1</button>
  </div>
</body>

<script type="text/javascript">
  Vue.config.productionTip = false;

  const vm = new Vue({
    el: '#root',
    data: {
      number: {
        a:1,  //Monitor a
        b:1
      }
    },
    watch:{ 
      /Monitor the change of an attribute in the multi-level structure/
      'number.a':{
        handler(newValue,oldValue){
        }
      }
    }
  })
</script>
Understand deep monitoring through this case-testing a and b Change of
<head>
  <script text="text/javascript" src="../js/vue.js"></script>
</head>
<body>
  <div id="root">
    <h3>a The value of is:{{number.a}}</h3>
    <button @click="number.a++">Let me a+1</button>
  </div>
</body>

<script type="text/javascript">
  Vue.config.productionTip = false;

  const vm = new Vue({
    el: '#root',
    data: {
      number: {
        a:1,  //Monitor a
        b:1
      }
    },
    watch:{ 
      number:{
        deep: true,  /Depth detection on/
        handler(newValue,oldValue){}
      }
    }
  })
</script>
  • Depth monitoring: the watch in ❶ Vue does not monitor the change of the internal value of the object by default (layer 1); ❷ configure deep:true to monitor the changes of internal values of objects (multiple layers).
  • Note: ❶ Vue can monitor the changes of internal values of objects, but the watch provided by Vue cannot by default! ❷ when using watch, decide whether to adopt deep monitoring according to the specific structure of data.

▲ comparison between watch and computed

  • The difference between watch and computed: all functions that can be completed by ❶ computed can be completed by watch; ❷ the functions that can be completed by watch may not be completed by computed. For example, watch can perform one-step operation.
  • Two important principles: ❶ for the functions managed by Vue, it is better to use Ctrip ordinary functions, so that the point of this is the vm or component instance object; ❷ for all functions not managed by Vue (timer callback function, ajax callback function, etc.), it is best to carry the Ctrip arrow function, so that the point of this is the vm or component instance object.

8. Bind class and style

binding class style
<head>
  <script text="text/javascript" src="../js/vue.js"></script>
</head>
<body>
  <div id="root">
    /binding class style--String writing,Apply to:The class name of the style is uncertain,Dynamic assignment required/
    <div class="basic" :class="mood" @click="changeMood">{{name}}</div><dr/>
    /binding class style--Array writing,Apply to:The number and name of styles to bind are uncertain/
    <div class="basic" :class="classArr">{{name}}</div><dr/>
    /binding class style--Object writing,Apply to:Determine the number and name of styles to bind,But you have to decide whether to use it dynamically/
    <div class="basic" :class="classObj">{{name}}</div><dr/>
    
    <div class="basic" :style="{fontSize: fsize+'px'}">{{name}}</div>
    /binding style style--Array writing/
    <div class="basic" :style="styleObj">{{name}}</div>
    /binding style style--Object writing/
    <div class="basic" :style="styleArr">{{name}}</div>
  </div>
</body>

<script type="text/javascript"> /basic,normal And happy They are all written styles/
  Vue.config.productionTip = false;

  const vm = new Vue({
    el: '#root',
    data: {
      name: 'Shang Silicon Valley',
      mood: 'normal',
      classArr: ['atguigu1','atguigu2','atguigu3'],  /atguigu1,atguigu2,atguigu3 They are all written styles/
      classObj: {
        atguigu1:false,
        atguigu2: false
      },
      fsize: 40,
      styleArr: [{
        color: 'red',
        fontSize: '40px'
      },{
        backgroundColor: 'bull',
      }],
      styleObj: {
        color: 'red',
        fontSize: '40px'
      }
      styleObj2: {
        backgroundColor: 'bull',
      }
    },
    methods: { 
      changeMood:{
       this.mood = 'happy',
      }
    }
  })
</script>

9. Conditional rendering

▲ v-if

  • Writing method: v-if = "expression" v-else-if = "expression" v-else = "expression"
  • Note: v-if can be used together with v-else-if and v-else, but the structure must not be "broken". It is applicable to scenes with low switching frequency. The feature is that DOM elements that are not displayed are directly removed.

▲ v-show

  • Writing method: v-show = "expression"
  • Note: DOM elements not shown in the feature are not removed and are applicable to scenes with high switching frequency.

10. List rendering

▲ basic list v-for instruction

<body>
  <div id="root">
    <!--Traversal array-->
    <ul>
      <li v-for="(p,index) in persons" :key="index">{{p.name}}-{{p.age}}</li>
    </ul>

    <!--Traversal object-->
    <ul>
      <li v-for="(value,k) of car" :key="k">{{k}}-{{value}}</li>
    </ul>

    <!--Traversal string-->
    <ul>
      <li v-for="(char,index) of str" :key="index">{{index}}-{{char}}</li>
    </ul>

    <!--Traverse the specified number of times (Use less) -->
    <ul>
      <li v-for="(number,index) of 5" :key="index">{{number}}-{{index}}</li>
    </ul>
  </div>
</body>

<script type="text/javascript">
  Vue.config.productionTip = false;
  new Vue({
    el: 'root',
    data: {
     persons: [
       {id:'001',name:'Zhang San',age:'18'},
       {id:'002',name:'Li Si',age:'17'},
       {id:'003',name:'Wang Wu',age:'18'},
     ],
     car: {name:'audi A8',price:'70 ten thousand',color:''},
     str: 'hello'
    }
  })
</script>
  • v-for instruction: ❶ used to display list data; ❷ syntax v-for = "(item, index) in XXX": key = "YYY"; ❸ traversable: array, object, string (used less), specified number of times (used least).

▲ key principle

Interview question: what is the role of the key in react and vue? (internal principle of key)

  1. Role of key in virtual DOM: key is the indicator of the virtual DOM object. When the data changes, Vue will generate a new virtual DOM according to the new data, and then Vue will compare the differences between the new virtual Dom and the old virtual dom. The comparison rules are as follows:
  2. Comparison rules: ⑴ The same key as the new virtual DOM is found in the old virtual DOM: ① if the content in the virtual DOM does not change, directly use the previous real DOM! ② If the content in the virtual DOM changes, a new real DOM is generated, and then the previous real DOM in the page is replaced;
    ⑵. The same key as the new virtual DOM is not found in the old virtual dom. Create a new real Dom and render it to the page.
  3. Possible problems caused by using index as key: ⑴ If the data is added, deleted and destroyed in reverse order (unnecessary real DOM updates will occur = = > the interface effect is OK, but the efficiency is low);
    ⑵. If the structure also contains the dom of the input class (an error will occur, DOM update = = > there is a problem with the interface).
  4. How to select a key in development?
    ⑴. It is better to use the unique identifier of each data as key, such as id, mobile phone number, id card number, student id number and so on. ⑵. If there are no destructive operations such as adding or deleting data in reverse order, it is only used to render the list for display. There is no problem using index as the key.

▲ list filtering

<body>
  <div id="root">
    <h2>Personnel list</h2>
    <input type="text" placeholder="Please enter a name" v-model="keyWord">
    <ul>
      <li v-for="(p,index) of filPerons" :key="index">
        {{p.name}}-{{p.age}}-{{p.sex}}
      </li>
    </ul>
  </div>
</body>

<script type="text/javascript">
  Vue.config.productionTip = false;
  new Vue({
    el: '#root'
    data: {
      keyWord:'',
      persons: [
        {id:'001',name:'Ma Dongmei',age:'19',sex:'female'},
        {id:'002',name:'Zhou Dongyu',age:'20',sex:'female'},
        {id:'003',name:'Jay Chou',age:'21',sex:'male'},
        {id:'004',name:'Wen zhaolun',age:'22',sex:'male'}
      ],
      filPerons: [],
    }
    watch: {
      keyWord: {
      immediate: true,  /Execute as soon as you come,Equivalent to giving filPerons assignment/
      handler(val){
        this.filPerons = this.persons.filter((p)=>{
          return p.name.indexOf(val) !== -1
        })
      }
    }
  })
</script>

Part II Vue cli

Part III Vue router

Part IV vuex

Part V element UI

Part VI vue3

For two weeks, please wait patiently

Topics: Front-end Vue