Getting started with Vue (lifecycle)

1, What is Vue

Vue is a [progressive] JavaScript framework for building user interfaces (UIS)

Official website: Vue.js

vue realizes the separation of front and rear ends

Development tool: HBuilderX

2, Differences between libraries and frameworks

2.1 Library is essentially a collection of functions. Each time the function is called, a specific function is implemented, and then the control is handed over to the user

Representative: jQuery    

The core of jQuery Library: DOM operation, that is, encapsulating DOM operation and simplifying DOM operation

2.2 framework is a complete solution. When using the framework, you need to put your code in the appropriate framework    Where appropriate, the framework will call your code at the right time  
      Representative: vue  
      The framework defines its own programming mode and is a complete solution
      When using a framework, the framework controls everything. We just need to write code according to the rules
      The framework is highly intrusive (from beginning to end)

3, Introduction to mvvm

mvvm is a better UI mode solution. mvvm automatically synchronizes data in both directions through two-way data binding

   MVVM ===> M / V / VM
    M: Model data model
    5: V iew view
    VM: ViewModel view model      Virtual dom

    V (modify data) - > m
    M (modify data) - > V
    Data is the core

Note 1: Although the MVVM model is not fully followed, Vue's design is undoubtedly inspired by it. Another js framework "knockout" completely follows the MVVM model

Note 2: when learning Vue, you should change your mind: "don't think about how to operate DOM, but how to operate data!!!"


4, Install Vue

4.1 cdn download (network connection required)
BootCDN - Bootstrap Chinese open source project free CDN acceleration serviceBootCDN - Bootstrap Chinese open source project free CDN acceleration serviceBootCDN - Bootstrap Chinese open source project free CDN acceleration service   es6 programming

<!-- Development environment version with helpful command line warnings -- >

 <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
 
  <!-- Production environment version, optimized size and speed -- >
 <script src="https://cdn.jsdelivr.net/npm/vue"></script>

  4.2 Manual Download  


      <!-- Development environment version with helpful command line warnings -- >
      <script src="dist/vue.js"></script>

      <!-- Production environment version, optimized size and speed -- >
      <script src="dist/vue.min.js"></script>
 

5, Getting started with vue

Case 1:

1. If there is no prompt, select the syntax prompt Library in the lower right corner and check vue.2.x (first import Vue dependencies: < script                           src=" https://cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.js "></script>)  )

vue codes are divided into three blocks:

    ① Define boundary

    ② Binding boundary: create vue instances and bind them together by id. all variables involved are defined in the data of vue instances    

③   Return data through method.    

Create a new project:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<!-- vue Related dependencies of -->
		<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.js"></script>
	</head>
	<body>
		<!-- Define boundary   Es6 Concrete embodiment of -->
		<div id="app">
			<h3>{{msg}}</h3>
		</div>
	</body>
	<script type="text/javascript">
		// Binding boundary
		new Vue({
			el:'#app',
			data() {
				return {msg:'vue Your uncle'};
			}
		})
	</script>
</html>

The operation is as follows:

There are two other ways to write data

  ① Return data through json object:

data:{
			msg:'json'
		}
data:function(){
			return {msg:'vue Your uncle'}
		}

Case 2

Vue data bidirectional binding:

Once the virtual dom detects that a node has changed, the data corresponding to that node will also change

v-model: instructions of vue

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<!-- vue Related dependencies of -->
		<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.js"></script>
	</head>
	<body>
		<!-- Define boundary   Es6 Concrete embodiment of -->
		<div id="app">
			<h3>{{msg}}</h3>
			<input type="text" v-model="msg"/>
			<h3>{{msg}}</h3>
			<h3>{{msg}}</h3>
     		<h3>{{msg}}</h3>
		</div>
	</body>
	<script type="text/javascript">
		// Binding boundary
		new Vue({
			el:'#app',
			data() {
				return {msg:'vue Your uncle'};
			}
		})
	</script>
</html>

The operation is as follows:

  Case 3

① All methods are written in methods, which are also json objects

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.js"></script>
		<title></title>
	</head>
	<body>
		<div id="app">
			<h3>{{msg}}</h3>
			<input type="text" v-model="msg" />
			<button v-on:click="getMsg">Gets the contents of the input box</button>
		</div>
		<script type="text/javascript">
			//Binding boundary
			new Vue({
				el:'#app',
				data(){
					return{msg:'vue Your uncle'}
				},
       // Fill in all methods in methods
				methods:{
					getMsg(){
						alert(this.msg);
					}
				}
			})
		</script>
	</body>
</html>

Operation results:  

  6, Life cycle of vue

Instance life cycle hook (just understand)
    When each Vue instance is created, it goes through a series of initialization processes -- for example, setting data listening, compiling templates, mounting the instance to the DOM, and updating the DOM when the data changes.
    At the same time, some functions called life cycle hooks will be run in this process, which gives users the opportunity to add their own code at different stages.
    This process is similar to Servlet life cycle and related methods. See "Vue lifecycle. PNG" for details of instance life cycle

① Life cycle diagram:

   

Hook function  

beforeCreate: just after new Vue(), the data has not been mounted yet. It is just an empty shell

create: data can be used or changed at this time. Changing data here will not trigger the updated function

beforeMount: the virtual dom has been created and will be rendered soon. You can also change the data here without triggering updated

Mounted: at this time, the component has appeared in the page, the data and real dom have been processed, and the events have been mounted

update: the data has been changed and the dom has been re render ed

Destroyed: destroyed

Lifecycle. html file:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<script src="https://cdn.bootcss.com/vue/2.6.10/vue.js"></script>
	</head>
	<body>
		<div id="d1">
			<div>number:{{number}}</div>
			<div>{{detail()}}</div>
			<input type="text" v-model="number" />
		</div>
		<script>
			var data = {
				number:999,
				msg:null
			};
			var vm = new Vue({
				el:'#d1',
				data:data,
				methods:{
					detail:function(){
						return "Use methods to interpolate:"+this.msg;
					}
				},
				beforeCreate:function(){
		            console.log('beforeCreate:just new Vue()After that, at this time, the data has not been mounted, it is just an empty shell')           
		            console.log(this.msg)//undefined
		            console.log(document.getElementsByClassName("myp")[0])//undefined
		        },
		        created:function(){
		            console.log('created:At this time, the data can be used or changed,Changing data here will not trigger updated function')
		            this.msg+='!!!'
		            console.log('Here, you can count the penultimate chance to change the data before rendering without triggering other hook functions. Generally, you can obtain the initial data here')
		            console.log('Next, start to find the template corresponding to the instance or component, and compile the template into virtual dom Put into render Prepare rendering in function')
		        },
		        beforeMount:function(){
		            console.log('beforeMount: fictitious dom It has been created and will be rendered soon,Data can also be changed here without triggering updated')
		            this.msg+='@@@'
		            console.log('Here, you can change the data for the last time before rendering without triggering other hook functions. Generally, you can obtain the initial data here')
		            console.log(document.getElementsByClassName("myp")[0])//undefined
		            console.log('Let's start render,Render reality dom')
		        },
		        // render:function(createElement){
		        //     console.log('render')
		        //     return createElement('div','hahaha')
		        // },
		        mounted:function(){ 
		            console.log('mounted: At this point, the component has appeared in the page, and the data and real information are displayed dom It's all taken care of,The events have been mounted')
		            console.log(document.getElementsByClassName("myp")[0])
		            console.log('You can operate it here dom Wait for things...')
		
		        //    this.$options.timer = setInterval(function () {
		        //        console.log('setInterval')
		        //         this.msg+='!'  
		        //    }.bind(this),500)
		        },
		        beforeUpdate:function(){
		            //The data cannot be changed here, otherwise it will fall into an endless loop
		            console.log('beforeUpdate:Triggered before re rendering')
		            console.log('then vue Virtual dom The mechanism will rebuild the virtual machine dom With the last virtual dom Tree utilization diff The algorithm is compared and re rendered')         
		        },
		        updated:function(){
		            //The data cannot be changed here, otherwise it will fall into an endless loop
		            console.log('updated:The data has been changed, dom Also re render complete')
		        },
		        beforeDestroy:function(){
		            console.log('beforeDestory:Execute before destruction( $destroy Method is executed when it is called),Usually deal with the aftermath here:Clear timers, clear non instruction bound events, and so on...')
		            // clearInterval(this.$options.timer)
		        },
		        destroyed:function(){
		            console.log('destroyed:Data binding and listening of components...All removed,Only left dom Empty shell, you can deal with the aftermath here')
		        }
			});
		</script>
	</body>
</html>

The operation is as follows:  

When you click the input box to change its contents, the beforeupdate and update functions will be triggered:

  7, Use of template pattern in vue life cycle

Create a project in eclipse and create a template class CodeTemplate (abstract class):

package com.zxy.base.test;

/**
 * You need to calculate the execution time of any piece of code
 *
 */
public abstract class CodeTemplate {
    public abstract void code();
//    Calculate the execution time of any piece of code
    public void handle() {
        long begin = System.currentTimeMillis();
        this.code();
        long end = System.currentTimeMillis();
        System.out.println((end-begin));
    }

    }

Code to be calculated for test:

package com.zxy.base.test;

public class ACode extends CodeTemplate {
    @Override
    public void code() {
        try {
            Thread.sleep(1050);
            for (int i=0 ;i<19999; i++) {
                System.out.println("Simulate database call");
            }
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        ACode aCode=new ACode();
        aCode.handle();
        
    }
}

The result is:

This case is equivalent to hook function, how to render virtual dom to low, by this.code(); It has the final say, and this is controlled by every programmer himself. The code method is called template method in the background, or hook method.  

It's over. I hope I can help you~~~~

Keywords: Javascript Front-end Vue.js

Added by wolfraider on Wed, 27 Oct 2021 20:39:52 +0300