Development framework VUE technology application summary

Keywords: Javascript Front-end Vue Vue.js

catalogue

VUE Foundation

MVVM design

VUE binding principle design

Virtual DOM tree analysis

VUE programming steps and Practice

Binding and instruction application

Binding style analysis (understand):

Application of life cycle function

Ajax requests in Axios mode

Get request

Post request

VUE component development

Component design

Basic steps

Operation analysis

Transfer parameters between components

Single page application practice (SPA)

Basic steps

Global components such as page headers:

Route jump

Routing parameters

Installation vue scaffold

Scaffold folder structure:

Lazy loading application practice

Asynchronous deferred loading:

Full lazy loading:

HTTP proxy cross domain:

vue.config.js settings

main.js

Avoid style conflicts between components

watch + Event modifier + anti shake:

Slot technology application

Vuex data management

Application scenario

Composition analysis (3 parts)

The variables in state are used in the component

Modify the variable value in state in the component

In the component, make an ajax request first, and then modify the variable value in state

TypeScript   Basic grammar

Variable:

Function:

Modular development:

Introduction to Vue3 new features

principle

ES6 Proxy proxy object:

Practice in main.ts

Page / component

VUE Foundation


MVVM design


MVVM: interface View + Model + View Model

VUE binding principle design


Accessor properties + virtual DOM tree
When the variable is modified: the accessor property notifies, and the virtual DOM tree scans and updates only the affected elements

Virtual DOM tree analysis

Advantages of virtual DOM tree:
(1) . small: contains only elements that may change.
(2) Fast traversal search
(3) . high modification efficiency: only the affected elements are modified.
(4) . avoid duplicate coding: add, delete, modify and check the code of the encapsulated DOM

VUE programming steps and Practice


Vue function 3 steps:
(1) . create an enhanced interface first:
a. The entire interface must be contained under a unique parent element:
Usually
b. Element contents that may change are marked with {{custom variable name}}
c. The element that triggers the event is marked with @ click = "custom handler name"
(2) . then create a new Vue() object, where el: points to the page area to be monitored by new Vue()
(3) . define the model objects data and methods in the new Vue() object
a. All variables required for the interface are placed in data
b. All event handling functions required for the interface are placed in methods


Binding and instruction application


(1) . if the content of the element needs to change automatically with the variable: {undefined {}}
(2) . if the attribute value of the element needs to change automatically with the variable:
(3) . control the display and hiding of an element: v-show / / use display:none to hide the element
(4) . control the display of one of two elements: v-if v-else / / hide the element by deleting the element
(5) . select one of multiple elements to display: v-if v-else-if v-else
(6) . as long as multiple element composition lists with the same structure are generated repeatedly: V-for: key = "unique ID"
Stress: why do you have to add: key = "i"? Add a unique identifier to each copy of the element. When modifying the value of an element in the array, to avoid rebuilding the whole list, you only need to modify a copy of DOM element! Improve modification efficiency.
(7) . just bind event: @ $event
(8) . prevent users from briefly seeing {undefined{}}: v-cloak and v-text
(9) . just bind the original HTML code fragment content: v-html
(10) . if the content of the element is bound only once when it is first loaded, it will not change after: v-once
Optimization: reduce the number of elements in the virtual DOM tree.
(11) {undefined {}} in protected content is not compiled: v-pre
(12) In the future, just want to get the value or status of the form element: v-model

Binding style analysis (understand):


(1) If you need to modify a css attribute precisely, bind style:
a. < element style = "fixed style": style="{css attribute: variable name,...}"
 

data:{
   Variable name:css Attribute value
	... : ...
}

b. < element style = "fixed style": style = "variable name"

data:{
   Variable name:{
	css Attribute name: Attribute value,
	... : ...
   }
  }

(2) class is bound as long as multiple css attributes of an element are modified in batch
a. < element class = "fixed class": class="{class name: variable name,...}"

data:{
   Variable name:true or false,
   ... : ...
}

b. < element class = "fixed class": class = "variable name"

data:{
      Variable name:{
	    class name:true or false,
    ... : ...
   }
}

 

Application practice of computing attributes
In the future, as long as an attribute value is dynamically calculated according to the values of other variables, the calculation attribute is used:
< element > {undefined {calculated attribute} < / element >

new Vue({
  el:"#app",
  data:{...},
  methods:{...},
  computed:{
    Calculated attribute name(){
      Calculation process
      return Calculation results
    }
  }
})

Application of life cycle function

vue life cycle consists of 4 stages and 8 hook functions

(1) . create

created(){ ... }
beforeMount(){ ... }

(2) . mount

mounted(){ ... Often send here ajax request ... }
beforeUpdate(){ ... }

(3) . update

updated(){ ... }
beforeDestroy(){ ... }

 

(4) . destroy

destroyed(){ ... }

Axios Ajax requests in

Just in vue Send ajax requests in axios
axios.defaults.baseURL = "public base address part of server-side interface"

Get request

GET request:

axios.get(
  "Relative path of server-side interface address",
  {
    params:{ Parameter name: Parameter value, ...  }
  }
).then(result=>{
  ... result.data...
})

Post request

POST request:

axios.post(
  "Relative path of server-side interface address",
  "Parameter name 1=Parameter value 1&Parameter name 2=Parameter value 2&..."
).then(result=>{
  ... result.data...
})

  Emphasis: in vue Internal use axios , an arrow function must be used in then to keep this in then consistent with the external this, both pointing to the current new Vue() object

VUE component development

Component design

As long as you want to reuse an independent functional area, use components:
(1) . define components
Vue. Component (component tag name, {undefined)
template:HTML content fragment,
Data() {return {variable}},
//The rest are exactly the same as new Vue()
})
(2) . using custom components in HTML
< component tag name / > or double label is also OK
(3) . principle: new Vue() scans the custom component label,
a. The HTML content in the template of the component replaces the < component tag > position in the page.
b. And create a miniature vue type object for this small area.
1) . call the data() function of the component to create an exclusive data object copy for the current component copy.
2) . introduce the methods and other contents of the component object into the copy of the current component object
 

Basic steps

a. Get the page and divide the functional area first
1) . from top to bottom, areas are divided according to different functions
2) . divided by reuse
b. Create a separate. js file for each component, which contains a component object and its content
c. Bring all components into a unique and complete html page, and

Add a parent component label to the.

Operation analysis

a. new Vue() scan

, find the parent component label, create and replace the parent component
b. The parent component scans its internal template content and creates and replaces child components

Component type
a. Root component: new Vue()
b. Global component: Vue.component(...)
c. Sub assembly: Step 3
1). var sub component object name = {undefined
The content must meet the requirements of the component
}
The sub component object name must be hump named
2) . in parent component object: {undefined
... ...
components {sub component object name,...}
}
The sub component object name must be hump named
3) . the parent component template uses < child component tag name / > to introduce child component content
components will automatically translate the hump naming of sub component object names into - separated
Therefore, when using subcomponent labels, separate multiple words with -
 

Transfer parameters between components

a. Parent component to child component
< sub component: custom attribute name = "parent component variable" >
b. Sub assembly:
props: [custom attribute name]
Result: in the subcomponent, the "custom attribute name" in props is exactly the same as the variable usage in the subcomponent's own data!

Single page application practice (SPA)

Basic steps

Step 1: create a unique and complete HTML page first

1) . contains vue basic page structure

  <div id="app"> new Vue({el:"#app"})

2) . introduce all necessary documents and components

  vue-router.js, Other pages or component files, router.js Router object file

 

Step 2: create a separate file for each page component. Each page component is actually a sub component

Step 3: create router.js file, for example:

 

1) Create routing dictionary object

1)Create routing dictionary object

  var routes=[
    {path:"/", component:Home page component object name},
    {path:"/Relative path" , component: Other page component object names},
    {path:"*", component: 404 Page component object }
  ]

2) . create a router object and transfer the routing dictionary object into the router object

  var router=new VueRouter({ routes })

3) . add the router object to new Vue()

   new Vue({ el:"#app", router })

Global components such as page headers:


a. Create a separate file to save the contents of the header component
b. Use Vue.component("my header", {...}) to create the page header as a global component
c. Introduce the header component file in the only complete HTML page
d. Use header component labels: 2 kinds:
1) . if all pages have a uniform header:
Just above the outside of the only complete html page
2) . if some pages have headers and some pages have no headers:
It is only placed in the template in the component that needs the page header
 

Route jump

a. html: Text
b. js: this.$router.push("/ relative path")

Routing parameters

a. Modify routing Dictionary:

  {path:"/Relative path/:Custom parameter name", component:Page component object, props:true}

b. When jumping:

  <router-link to="/Relative path/Parameter value"
  or
  this.$router.push("/Relative path/Parameter value")

 

c. Next page continues:

 1). props:[ 'Custom parameter name' ]
 2). Can be"Custom parameter name"It can be used as a binding or in a program

Installation vue scaffold

(1) . set npm to use domestic Taobao image warehouse by default:

npm config set registry http://registry.npm.taobao.org
  alternative : npm i -g cnpm --registry=http://registry.npm.taobao.org


 

(2) . install tools that can repeatedly generate project scaffold Codes:

npm  i   -g  @vue/cli
  alternative : cnpm i -g @vue/cli

(3) . start vue scaffold project

npm run serve

 

(4) . open the browser and enter in the address bar:

 http://localhost:8080

Scaffold folder structure:

(1) The only complete HTML page: one is divided into three:

 

a. public folder
1) . the picture img folder is placed under the public folder
2) . the compressed version of the third-party css and the compressed version of the third-party js are placed in the public folder
3) The only complete HTML file, index.html, introduces third-party css and js into the head

b. src/App.vue
1) Only common header components are included under and
2).

1). import introduces App.vue, router, axios, and other global components
2) . turn the global component object into a real global component: Vue.component("component tag name", global component object)
3) . configure axios and put it into the prototype object:
axios.defaults.baseURL = "server side basic path"
Vue.prototype.axios=axios;
 

(2) . create. vue component files for each page and put them in the src/views folder. In each. vue file:

a. The tag contains the HTML content of this page
b. The content of js in is exactly the same as that in the previous four days, including binding, instructions, functions, life cycle, axios requests, etc. How to use it the first four days, how to use it here.

(3) . the routing dictionary and router object are in the src/router/index.js file

a. Only import the home page component object. Do not import other page components too early
b. Home page component in routing Dictionary: {path:"/", component: home page component object}
c. Other page components are loaded lazily:
{undefined
Path: '/ relative path',
Component: () = > Import (/ * webpackchunkname: "component name" * / '... / views / other page components. vue')
}


(4) . the global components are placed in the src/components folder and in the. vue file of each global component.

Global components must be introduced in main.js and converted into real global components with Vue.component() before they can be used in the HTML of other components.

(5) . when running, the router object of the router monitors the path change of the browser address bar,

Find the corresponding page component content, first replace the content in App.vue, then main.js, and then replace the App.vue component content containing the page content to be loaded with the only complete index.html

Location.

Lazy loading application practice

Asynchronous deferred loading:

src/router/index.js
//Do not import Details from "../views/Details"
const routes=[
  ...
  {
    path:"/details/:lid",
	component: () => import(
		/* webpackChunkName: "details" */ 
		'../views/Details.vue'
	),
    props:true
]

 

Full lazy loading:

Create vue.config.js from the project root directory

Project root directory creation vue.config.js

module.exports={
  chainWebpack:config=>{
    config.plugins.delete("prefetch")
    //Delete the link with prefetch attribute at the beginning of index.html, and do not asynchronously download page component files that are not needed temporarily
  },
}

HTTP proxy cross domain:

vue.config.js settings

module.exports={
  ... ,
  devServer: {
    proxy: {
      '/': {
        target: `Server side interface address common base path`,
        changeOrigin: true
      }
    }
  }
}

main.js

axios.defaults.baseURL="Server side common base path"
  • 1

(3) . reference this.axios.get("/ interface address relative path"). Then (result = > {...})

Avoid style conflicts between components

(1) Option 1

<style scoped>

 

(2) Option 2

<template>
   <Component parent element class="Component name">
  </template>
  <style>
   .Component name>Child Selector { ... }
  </style>

watch + Event modifier + anti shake:

(1) When you want to perform an operation automatically as soon as the variable changes:

data(){
     return { variable: value }
  },
watch:{
    variable(){
        Action to perform
}
}

(2) . event modifier:

@Event.13 press enter to execute
@Event. stop prevent bubbling
@Event. prevent prevents default behavior

(3) . anti shake:


data(){
  return {
    ... ,
    timer:null
  }
},
methods:{
  Search method(){
    if(this.timer!=null){
      clearTimeout(this.timer)
    }
    this.timer=setTimeout(()=>{
      Formal find operation
    },waiting time)
  }
}


 

Slot technology application

(1) . as long as multiple components have the same structure, but the local contents are different, they can be implemented by slots
(2) How to:
a. First, create an additional shell component with slots and save the HTML+CSS+JS of the same part of other components. However, locations in the housing assembly that may change in the future are marked with
b. Redefine other components that use shell components:
1) . introduction of housing assembly with slot:

  import Enclosure component name from "./Housing assembly.vue"
  export default {
    components:{ Enclosure component name },
      ... 
  }

2) . in other components:

  <template>
    <Housing assembly :Required properties of shell components="variable">
      <Personalized content owned by the current component>
    </Housing assembly>
  </template>

(3) . named slot:
a. If multiple parts of a housing assembly will be replaced in the future, a named slot can be used
b. How to:
1) . in the housing assembly:


  <template>
    ...Public part...
    <slot name="Slot name 1"></slot>
    ...Public part...
    <slot name="Slot name 2"></slot>
    ...Public part...
  <template>

2) . other components using housing components:


 <template>
    <Housing assembly...>
      <template  #Slot name1 >
        Part I contents to be replaced
      </template>
      ...
      <template #Slot Name2 >
        Part II Contents to be replaced
      </template>
    </Housing assembly>
  </template>

Vuex data management

Application scenario

In the future, as long as multiple components need to share a batch of data, vuex can be used

 

Composition analysis (3 parts)

state section:

  state:{ //Save shared variables 
      variable:Initial value,
	  ... : ...
    }

 

Changes section:

 mutations:{ //Save methods that specifically modify variables 
	  set Variable name(state, New value){
		state.Variable name=New value
	  }
	  ... 
	}

actions section:


  actions:{ //Save a method that sends ajax requests first and then modifies variables 

  Method name(context, Parameter values sent to the server){
    axios.get or post(
	  "Interface address",
	  Parameter values sent to the server
	).then(result=>{
	  ...
	  context.commit("mutations Name of a method in", New value)
	  ...
	})
}
}

The variables in state are used in the component


a. import { mapState } from "vuex"
b. export default {undefined
computed:{undefined
... mapState(["name of a variable in state",...]),
Other calculation properties
}
}
c. A variable name in the available state is used for binding and instructions
d. js can read the variable value by using a variable name in this. state
 

Modify the variable value in state in the component

a. import { mapMutations } from "vuex"
b. export default {undefined
methods:{undefined
... mapMutations (["a method name in Mutations",...]),
Other methods
}
}
c. js, you can modify the variable value in state with a method name (argument value) in this. Variables
 

In the component, make an ajax request first, and then modify the variable value in state

a. import { mapActions } from "vuex"
b. export default {undefined
methods:{undefined
... mapActions (["name of a method in Actions",...]),
Other methods
}
}
c. js can send ajax requests using a method name (argument value) in this. Actions and modify the variable value in state.
 

TypeScript   Basic grammar

Variable:

var or let or const Variable name:data type=value;

Function:

(1) . definition:

Function function name (formal parameter: data type,...): return value type {undefined
... ...
}

(2) . number of uncertain parameters:

a. A single parameter is uncertain

function Function name(Formal parameter 1:data type, Formal parameter 2?:data type)...
or
function Function name(Formal parameter 1: data type, Formal parameter 2:data type=Default value)...

 

b. Multiple parameters are uncertain

function Function name(Formal parameter 1:data type, ...Formal parameter 2:data type[])...

(3) . heavy load:
a. First define an empty function declaration and list all possible overloads:

function Function name():return type;
function Function name(Formal parameter 1: data type):return type;
function Function name(Formal parameter 1: data type, Formal parameter 2:data type):return type;

 

b. Functions that formally implement functions:

 function Function name(){
      according to arguments The number of elements in determines the specific logic to be executed
    }

class new regulations
(1). class type name {/ / the attribute must be declared in advance before it can be used

Attribute 1: data type = initial value
    Attribute 2: data type = initial value
    ...
 

    //Constructor must define a data type
    constructor(Formal parameter 1:data type, Formal parameter 2:data type,...){
        this.Attribute 1=Formal parameter 1;
        this.Attribute 2=Formal parameter 2;
        ...
    }
    /*Method definition*/
  }

(2) . access modifier: in the future, as long as you want to control the use range of attributes in a class.


 class father{
       public Public attribute:data type=value
       protected Protected properties:data type=value
       private Private property:data type=value
       Parent function(){
         All three properties can be used
       }
    }
    class son extends father{
       Sub function(){
          Only public and protected attributes of the parent can be used
          Cannot use private property of parent
       }
    }
    Except father and son class Program areas outside: 
    Only parent can be used class Public properties of the object

(3) . interface: ensure that developers implement class members as required
a. Define the interface first:

interface  I Interface name{
  Attribute name:data type
  ...
  Method name(Formal parameter:data type, ...):return type;

b. Requirements for defining class implementation interfaces:

class Type name implements  I Interface name{
  Attribute name:data type=value
  ...
  Method name(Formal parameter:data type, ...):return type{
    Method implementation
  }
}

Modular development:

(1) . only one thing is thrown in the module:

  export default One thing
  import  alias  from "Relative path"

(2) . throw multiple things in the module at the same time:

  export { Multiple things are separated by commas }
  import { Separate the individual things you want with commas }  from  "Relative path"

Introduction to Vue3 new features

principle

Binding principle: ES6 Proxy proxy object + virtual DOM tree

ES6 Proxy proxy object:

Newly generated proxy object = new Proxy(Original object to protect or monitor, { 
      //Automatically triggered when someone tries to get the value of any element in the array
      get(Current object, Attribute name) { 
        console.log(`Someone tried to read arr Object ${Attribute name}member`)
        return Current object[Attribute name];
      },
      //Automatically triggered when someone tries to modify the value of any element in the array
     set(Current object, Attribute name, New value) {
        console.log(`Someone tried to modify it arr Object ${Attribute name}member`)
        Current object[Attribute name] = New value;
        return true; //Required: return to modify successfully!
      }
  });

//In the future, new proxy objects will be used instead of the original objects, but the usage is exactly the same as that of ordinary objects!

Practice in main.ts

a. Default:

   createApp(App).use(store).use(router).mount('#app')

b. Global components:

import Component object  from "Component file relative path
var app= createApp(App);
app.component('Component tag name', Component object name)
app..use(store).use(router).mount('#app')

 

c. Global instructions:

app.directive ("my-focus",{
	mounted(DOM element){
			DOM operation
	}	
})

d. axios: / / the axios object is a singleton mode. There is only one axios object in the whole project. It is used everywhere.
import axios from "axios"
axios.defaults.baseURL = "server side interface basic path"
//The singleton pattern can be referenced in any component without putting it into the prototype object -- Vue2 can also be used in this way.
 

Page / component

a. Lihe


import { defineComponent, ref, reactive, toRefs, watch, computed, onMounted } from 'vue';
import axios  from "axios" //axios object is a singleton mode. There is only one axios object in the whole project, and it is the same everywhere.
import Subcomponent object   from "Subcomponent relative path

export default defineComponent({
  components:{ Subcomponent object },
  directives:{
    "Custom directive name:{
       mounted(DOM element){
         DOM operation
       }
     }
  },
  setup(){ //
    const data=reactive({
      Interface required variables
    });
    //A variable that specifically deconstructs the original type
    let { Variable of original type, ... } = toRefs(data);
	//Variables that specifically deconstruct reference types
    let {Variable of reference type, ...} = data;

    const methods={
      Interface required method(){ ... use data Medium variable, no need to add this!But add.value Can use }
      Calculation properties: computed(()=>{ //There is no filter in vue3. The calculation attribute takes into account the filter function
         //Calculation process
         return Return value
      })
    }

    watch(Variables to monitor, ,(newVal, oldVal)=>{
		console.log(`The variable has changed and the new value is ${newVal}, Old value is ${oldVal}`)
		//What to do when a variable changes
	})

    //The declaration cycle must be import ed first and then called inside setup!
    onMounted(){ //Original mounted lifecycle hook function
        //axios requests do not need to add this
		axios.get(...).then(result=>{ ... })
    }

	return {
		...toRefs(data.value),
        ...methods
    }
  },
})

New declaration cycle hook function

  beforeCreate -> setup()
  created -> setup()
  beforeMount -> onBeforeMount
  mounted -> onMounted
  beforeUpdate -> onBeforeUpdate
  updated -> onUpdated
  beforeDestroy -> onBeforeUnmount
  destroyed -> onUnmounted



 

Posted by Ardivaba on Sat, 06 Nov 2021 22:25:01 -0700