It has nothing to do with the third stage
Progressive enhancement and graceful degradation
Progressive enhancement is to be compatible with the lower version and gradually improve to the higher version
Elegant downgrade is to complete the writing of the high version browser first, and to be compatible with the low version
Disabled tag disabled attribute
You can't use this attribute tag
What are the common js dom operations?
dom lookup
dom new creation
dom clone delete attribute operation
app classification
Mobile webapp is an app running on the mobile browser
Native app: the app downloaded from the mobile app store
Hybrid app: the page written by our front end (vue react html+css+js) embeds the page written by us i into the native project
es6 deconstruction assignment
Is a syntax for quickly assigning values to arrays or objects
Prototype design
Ink knife ink guest blue lake
Vue
Basic concept of vue
vue is the most popular front-end js framework (a tool for data processing and data binding)
Author: you Yuxi
He is a Chinese

Former google employee
What is it?
vue is a progressive bottom-up incremental MVVM framework for building user interfaces
Progressive: don't do anything other than your duty (that is, vue can be used locally in a project, it will not affect the unused location, or it can be used for the whole project)
Bottom up incremental development: first write a basic page, and then add various complex functions, which is a simple to cumbersome process
MVVM is a framework mode:
What is a framework
It is used to encapsulate some code blocks that have nothing to do with the business (that is, the functions of the project you write). We can use it to assemble to complete the specified project functions
Advantages of framework
It greatly improves the development efficiency (but it is troublesome for beginners to learn new grammar)
MVC
It was a framework pattern yesterday morning -- "mvvm" is a variant of mvc
It is to abstract a function of a project into different modules, and each module manages its own affairs, making development easier
M (model) model (in the future, we will automatically convert the model into data) to manage the data
V (view) (where users can see)
C (controller) controller is used to receive and display data
MVVM
Is a mode used in vue
M (model) model (in the future, we will automatically convert the model into data) to manage the data
V (view) (where users can see)
VM (ViewModel) is a data bridge between the view model data and the view (this bridge is more intelligent. It can find the data changes in the model or view. When one party changes, it will immediately notify the other party to make changes)
[the transfer of external chain pictures fails. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-OjdKnjRD-1624408588808)(.\img].bmp)]
Development purpose of vue
1. Solve the problem of data binding
2. Large single page SPA applications can be developed
3. Support componentization
HelloWord
1. We need to download: npm install -save vue
2. Start writing page code
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <!-- 1.First reference --> <script src="node_modules/vue/dist/vue.min.js"></script> </head> <body> <!-- M (model)Model (in the future, we will automatically convert the model into data) to manage the data V (view) View (where the user can see) VM (ViewModel)The view model is a data bridge between the model data and the view (this bridge is more intelligent. It can find the data changes in the model or view. When one party changes, it will immediately notify the other party to make changes) --> <!-- 2.newly build V layer --> <div id="demoDiv"> {{text}}------{{num}} </div> <script> // 3. Create a new vm layer (that is, vue instance) new Vue({ // 4. Associate model and view layer el:"#demoDiv", data:{ //5 model layer text:"How old are you", num:18 } }) </script> </body> </html>
Rendering mode of vue
Template syntax template expression double curly bracket assignment method
effect:
It is used to parse an expression in vue (an expression can return a result through some calculation), although it can process some data in {}}
However, it is not recommended to write too complex logic in {}} in vue (because the view layer is displayed, and it is inappropriate for you to deal with too complex logic in it)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="node_modules/vue/dist/vue.min.js"></script> </head> <body> <div id="demoDiv"> <h1>Template syntax</h1> <!-- {{}}----->Template syntax template expression double curly bracket assignment method effect: Used in vue Parsing expression in (expression is a formula that can return results through some calculation) --> <h1>{{text}}</h1> <h1>{{num}}</h1> <h1>{{bool}}</h1> <h1>{{arr[2]}}</h1> <h1>{{obj.age}}</h1> <hr> <h1>{{updata.toUpperCase()}}</h1> <h1>{{updata.substr(1,3)}}</h1> <h1>{{arr.length}}</h1> </div> <script> new Vue({ el:"#demoDiv", data:{ text:"I'm a string", num:666, bool:true, arr:[111,2222,3333,4444], obj:{ name:"xixi", age:18 }, updata:"abcdefg" } }) </script> </body> </html>
Declarative rendering and data driven
The core of vue is to allow us to use concise template syntax for declarative data rendering
Declarative rendering: we tell the program what I want to do, and the program will complete automatically
Imperative rendering: when the native commands are all commands, we need to tell the program how to go step by step before it will follow our instructions
Data driven
vue will monitor the model and view all the time. When one party changes, the other will also change
Summary:
Do not put double quotation marks in the double braces of vue
instructions
What are the properties of HTML?
Is used to extend the function of HTML tags
Attribute syntax?
Write in the open tag of HTML and attribute = "attribute value"
vue instructions
Instruction is a special attribute with v-prefix (a technology of extending HTML tag function with v-prefix in vue)
Syntax of vue instruction
It is written in the open tag of HTML, and the instruction = "instruction value" note: multiple instructions can be written in a start tag, and multiple instructions are separated by spaces
v-model
v-model instruction
Function: mainly used for two-way binding of data on forms
Syntax: v-model = variable
Note: the v-model instruction must be bound to the form element
The core function of Vue framework is bidirectional data binding. Bidirectional means that HTML tag data is bound to Vue objects, and the data in the opposite direction is also bound
The v-model instruction is used to realize bidirectional data binding, and the view data and model data are bound to each other
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="node_modules/vue/dist/vue.min.js"></script> </head> <body> <div id="demoDiv"> <h1>v-model instructions</h1> <!-- Can be associated data Data and form elements --> <!-- Bidirectional binding---->The data changes in the view vm The layer will find that it will actively modify the data of the model layer When the model data changes, the view changes and vice versa --> <input type="text" v-model="inputval"/> <h1>{{inputval}}</h1> <hr> <!-- Check boxes are also form elements So you can also use v-model But it will put the data in true false Medium switching --> <input type="checkbox" v-model="bool"/> <h1>{{bool?"You checked it":"You didn't check it"}}</h1> </div> <script> new Vue({ el:"#demoDiv", data:{ inputval:"", bool:true } }) </script> </body> </html>
Principle of bidirectional binding
vue data bidirectional binding is realized by data hijacking combined with publisher subscriber mode
Data hijacking: data interception. When we access or set the properties of an object, it will trigger the object Defineproperty() function to intercept (hijack), and then return (get) or set the value of the property of the object. And react when the data changes.
Publisher subscriber mode: it defines a one to many dependency between objects. When the state of an object changes, all objects that depend on it will be notified.
v-show
v-show instruction
Function: controls the display and hiding of an element
Syntax: v-show = expression
Determines whether to display the current element according to the true or false result of the expression
true indicates that the element is displayed; False (default) means that the element is hidden
The element always exists, but display: none is set dynamically
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="node_modules/vue/dist/vue.min.js"></script> </head> <body> <div id="demoDiv"> <h1>v-show</h1> <input type="checkbox" v-model="bool"/>{{bool?"display":"cancel"}} <p v-show="bool">I want to show and hide</p> </div> <script> new Vue({ el:"#demoDiv", data:{ bool:true } }) </script> </body> </html>
v-on
v-on instruction
Function: binding event listening for HTML elements
Syntax: v-on: event name = 'function name ()'
Short form syntax: @ event name = 'function name ()'
Note: the function is defined in the methods configuration item
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="node_modules/vue/dist/vue.min.js"></script> </head> <body> <div id="demoDiv"> <h1>v-on</h1> <button v-on:click="fun()">Click my print</button> <button @click="fun()">Click on my short print content</button> </div> <script> new Vue({ el:"#demoDiv", data:{ }, // The function is written in the same location as data el and wrapped with methods methods:{ fun(){ console.warn("How are you") } } }) </script> </body> </html>
v-for
v-for instruction
Function: traverse the data in data and display the data on the page
Syntax: v-for = '(item, index) in arr'
item represents the element obtained from each traversal
Index indicates the index of the item. Optional parameters
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="node_modules/vue/dist/vue.min.js"></script> </head> <body> <div id="demoDiv"> <h1>v-for</h1> <ul> <li v-for="(v,i) in arr">{{v.name}}------{{v.age}}</li> </ul> <table border="1"> <tr v-for="(xiaoming,xiaohong) in arr"> <td>{{xiaohong}}</td> <td>{{xiaoming.name}}</td> <td>{{xiaoming.age}}</td> </tr> </table> </div> <script> new Vue({ el:"#demoDiv", data:{ arr:[ {name:"xixi1",age:118}, {name:"xixi2",age:218}, {name:"xixi3",age:183}, {name:"xixi4",age:184}, {name:"xixi5",age:185}, {name:"xixi6",age:186} ] } }) </script> </body> </html>
v-bind
v-bind instruction
Function: bind variables to html attributes
Syntax: v-bind: attribute name = 'expression' / abbreviation: attribute name = 'expression'
Bind a property:
Bind multiple properties (short form cannot be used):
<img v-bind='{src:myUrl, title: msg}' />
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="node_modules/vue/dist/vue.min.js"></script> </head> <body> <div id="demoDiv"> <h1>v-bind</h1> <a v-bind:href="ahref">{{text}}</a> <a :href="ahref">11{{text}}11</a> </div> <script> new Vue({ el:"#demoDiv", data:{ text:"I'll go to Baidu", ahref:"http://www.baidu.com" } }) </script> </body> </html>
v-if bucket
v-if v-else v-esle-if
v-if instruction
Function: judge whether to load fixed content
Syntax: v-if = expression
Determines whether to display the current element according to the true or false result of the expression
true indicates that the element is loaded; false means that the element is not loaded
The display and hiding of elements is to add and delete Dom elements
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="node_modules/vue/dist/vue.min.js"></script> </head> <body> <div id="demodiv"> <h1>v-if</h1> <input type="checkbox" v-model="bool"/> <p v-show="bool">I am v-show Element of</p> <p v-if="bool">I am v-if Element of</p> </div> <script> new Vue({ el:"#demodiv", data:{ bool:true } }) </script> </body> </html>
The difference between v-if and v-show
First of all, both have the same effect from the user's point of view. They both display and hide the elements on the page. The received data Boolean value true displays false hides
However, v-if is used to add and delete DOM elements, which has reached the goal of displaying and hiding v-show using css
Application scenario:
v-show consumes a lot of computer resources during initialization (displaying and hiding content with relatively low security)
v-if compares the resource consumption of the computer during switching (displaying and hiding the content with relatively high security)
v-else
Function: it must be used with v-if, otherwise it is invalid. Execute when the v-if condition is not true
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="node_modules/vue/dist/vue.min.js"></script> </head> <body> <div id="demodiv"> <h1>v-else</h1> <h1 v-if="bool">I am if Content of</h1> <p>v-if And v-else There can be no third party between</p> <h1 v-else>I am else Content of</h1> </div> <script> new Vue({ el:"#demodiv", data:{ bool:false } }) </script> </body> </html>+
v-else-if
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="node_modules/vue/dist/vue.min.js"></script> </head> <body> <div id="demodiv"> <h1>v-else-if</h1> <select v-model="text"> <option value="having dinner">having dinner</option> <option value="sleep">sleep</option> <option value="Eating">Eating</option> <option value="Sleeping">Sleeping</option> <option value="use the toilet">use the toilet</option> </select> <p v-if="text=='having dinner'">The user has selected a meal</p> <p v-else-if="text=='sleep'">The user chose to sleep</p> <p v-else-if="text=='Eating'">The user chose to eat at</p> <p v-else-if="text=='Sleeping'">The user chose to sleep</p> <p v-else-if="text=='use the toilet'">The user chose to go to the toilet</p> <p v-else>The user has no choice</p> </div> <script> new Vue({ el:"#demodiv", data:{ text:"" } }) </script> </body> </html>
v-text
v-text instruction
Role: manipulate plain text content in web page elements. {{}} is his other way of writing, which is to insert plain text into the web page
V-text is equivalent to {}}, {} is called template interpolation, and v-text is called instruction.
One difference is that when there is a lot of rendered data, curly braces may be displayed, commonly known as screen flashing
Screen flashing
① Rendering data using v-text
② The {}} syntax is used to render the data, but at the same time, the v-cloak instruction (used to keep on the element until the end of the associated instance for compilation) is used. Where should the v-cloak be placed? V-cloak does not need to be added to each label, but can be added to the label mounted by el
v-html and v-once
v-html instruction
What it does: Double braces interpret data as plain text, not HTML. In order to output real HTML, you need to use the v-html instruction
Syntax:
v-once instruction
Function: when the data changes, the content at the interpolation will not be updated (which will affect all attributes on the node)
Syntax:
{{text}}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="node_modules/vue/dist/vue.min.js"></script> </head> <body> <div id="demodiv"> <h1>v-html</h1> {{newhtml}} <div v-html="newhtml"></div> <h1>v-once One time interpolation</h1> <input type="text" v-model="text"> <p>{{text}}</p> <p v-once>{{text}}</p> <p>{{text}}</p> <p>{{text}}</p> </div> <script> new Vue({ el:"#demodiv", data:{ newhtml:"<h1>I'm a string tag</h1>", text:"I'm the default" } }) </script> </body> </html>
Listen / listen watch
Watch is used to monitor the contents of data model data. When the data changes, watch will trigger
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="node_modules/vue/dist/vue.min.js"></script> </head> <body> <div id="demodiv"> <input type="text" v-model="text"> </div> <script> new Vue({ el:"#demodiv", data:{ text:"I'm the default" }, // monitor watch:{ // Data you want to monitor: function (new value, old value){ // The logic you have to complete // } text(newval,oldval){ console.log(`${newval}-----${oldval}`) } } }) </script> </body> </html>
Calculation properties
Concept: as the name suggests, first, it is an attribute, and second, it has the special property of "calculation". Each time it gets its value, it does not return the result directly like ordinary attributes, but returns the result after a series of calculations. At the same time, as long as an attribute in data is referenced in its, when this attribute changes, the calculation attribute seems to be able to sniff the change and automatically re execute it.
The calculated attribute is an attribute, so it is written in the same level as el methods. Its main function is to calculate (calculate the data of data. When the data attribute changes, it will know and recalculate and return the results we want. When a piece of data shows different forms in different positions)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="node_modules/vue/dist/vue.min.js"></script> </head> <body> <div id="demodiv"> <h1>Why does too much logic written in the template with calculation attributes lead to failure of maintenance in the later stage</h1> <p>{{text}}</p> <p>{{text.toUpperCase()}}</p> <p>{{text.toUpperCase().substr(1,3)}}</p> <h1>Calculation properties</h1> <p>{{newatext}}</p> <p>{{newbtext}}</p> </div> <script> new Vue({ el:"#demodiv", data:{ text:"abcdefghijk" }, watch:{ }, // Calculation properties computed:{ // Data to be returned: function(){ // return processing operation // } newatext(){ // You must return return this.text.toUpperCase() }, newbtext(){ return this.text.toUpperCase().substr(1,4) } } }) </script> </body> </html>
The difference between calculated and methods
Why this idea
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="node_modules/vue/dist/vue.min.js"></script> </head> <body> <div id="demodiv"> <p>{{newtext}}</p> <p>{{showtext()}}</p> You will find that there is no difference between the two results </div> <script> new Vue({ el:"#demodiv", data:{ text:"abcdefg" }, watch:{ }, methods:{ showtext(){ return this.text.toUpperCase() } }, computed:{ newtext(){ return this.text.toUpperCase() } } }) </script> </body> </html>
If we call the calculated property multiple times, it is only executed once
However, we call the method several times and execute it several times, which is a great waste of resources
difference:
Computed properties are cached based on their dependencies. A computed property is re evaluated only when its related dependencies change.
As long as the method binding data is called, the method will always execute the function again.
Computing properties can save resources and performance in specific situations compared with methods
Differences between calculated properties and listeners:
When the value monitored by watch changes, it will be called. Watch can do some asynchronous processing or expensive operations when the data changes
Calculation attribute is the value of calculation dependency. It will be triggered when the dependent value changes.
Event object
The event object is the element information used to describe the event
$event
Modifier
The v-on instruction provides event modifiers to handle DOM event details
Key modifier
Key modifier: up, .down, .ctrl, .enter, .space, wait
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="node_modules/vue/dist/vue.min.js"></script> </head> <body> <div id="demodiv"> <!-- @event.Modifier ="method()" --> <input type="text" @keydown.ctrl="fun()"> </div> <script> new Vue({ el:"#demodiv", data:{ }, methods:{ fun(){ console.log("aaaaaaaaaa") } }, watch:{ } }) </script> </body> </html>
Event modifier
[Extension] event modifier
prevent modifier: block the default behavior of the event (submit submit form)
stop modifier: prevent event bubbling
Capture modifier: opposite to the direction of event bubble, event capture is from outside to inside
self: only events within its own scope will be triggered, and no child elements will be included
Once: only triggered once
Note: modifiers can be concatenated
interactive
Vue requests data in three ways: Vue resource, Axios and fetch. Vue resource is a plug-in officially provided by Vue, Axios is a third-party plug-in, and fetch es6 is native
Vue resource is in vue2 0 has stopped updating
axios is a secondary encapsulation of XHR objects using promise, which simplifies the syntax
fetch is native to es (it will be written in react)
axios
First experience
axios is a third-party data request library. Encapsulating XHR objects with promise is the most mainstream data request method today
Download before use
npm install --save axios
axios package
Life cycle and hook function
The life cycle is the process from creation to destruction of vue instances
Hook function: it is essentially a function, but it is a function that will be called automatically
Hook function of life cycle: it is the function that is automatically called during the process of vue creation and destruction (it can help us complete the automatically executed business under some specific conditions in vue)
Life cycle hooks:
beforeCreate (create instance)
created
beforeMount (start creating template)
mounted (creation completed)
beforeUpdate
updated (update completed)
beforeDestroy
destroyed
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="node_modules/vue/dist/vue.min.js"></script> </head> <body> <div id="demodiv"> <h1>{{text}}</h1> <button @click="text='I was changed'">Click my update</button> </div> <script> new Vue({ el:"#demodiv", data:{ text:"I am a string" }, methods:{ }, watch:{ }, computed:{ }, // life cycle // **beforeCreate (create instance)** // **created** // **beforeMount (start creating template)** // **mounted (creation completed)** // **beforeUpdate** // **updated (update completed)** // **beforeDestroy** // **destroyed** beforeCreate(){ console.log("Create instance") }, created(){ console.log("Instance creation completed") }, beforeMount(){ console.log("Start creating template") }, mounted(){ console.log("Creation complete") }, beforeUpdate(){ console.log("Start update") }, updated(){ console.log("Update complete") }, beforeDestroy(){ console.log("Start destruction") }, destroyed(){ console.log("Destruction complete") }, }) </script> </body> </html>
Custom filter
Filter function
Output the format data required by the front end without changing the data
Pit: during the interview, the interviewer or when communicating with colleagues in the future may be asked. Can you tell me about the built-in filter in vue?
The built-in filter has been discarded in 2.0. We need to customize the filter to use the filter
Global filter
The content defined by the global filter can be used in all instances in the page
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="node_modules/vue/dist/vue.min.js"></script> </head> <body> <div id="demodiv"> {{text|xiaoming}} </div> <div id="demodivb"> {{text|xiaoming}} </div> <script> // If the data displayed on the page is different from our renewal idea, we can format the display data with a filter // The global filter is defined before the instance Vue.filter("xiaoming",(val)=>{ // If it is greater than 5, keep 5 bits and add if(val.length>=5){ return val.substr(0,5)+"..." }else{ return val } }) new Vue({ el:"#demodiv", data:{ text:"I'm the first content Oh, Moda" } }) // ===================== new Vue({ el:"#demodivb", data:{ text:"Hehe hehe" } }) </script> </body> </html>
Local filter
Can only be used in the specified instance
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="node_modules/vue/dist/vue.min.js"></script> </head> <body> <div id="demodiv"> {{text|xiaohone}} </div> <div id="demodivb"> <!-- Cannot be used because local filters are defined --> {{text|xiaohone}} </div> <script> // The local filter is written in the specified instance at the same level as data new Vue({ el:"#demodiv", data:{ text:"Journey to the West" }, filters:{ xiaohone(val){ return "<<"+val+">>" } } }) new Vue({ el:"#demodivb", data:{ text:"The Dream of Red Mansion" } }) </script> </body> </html>
Summary:
On the premise of no conflict, the filter can be connected in series
Project environment configuration vue scaffold
preparation in advance
There must be node on the computer
Install Taobao image cnpm (not required, but can be installed when the network is slow)
npm install -g cnpm --registry=https://registry.npm.taobao.org
If an error is reported during installation, please connect the wifi of your mobile phone
use
1. Install Vue cli NPM install - G @ Vue / cli globally (you don't need to install Vue cli unless your computer reinstalls the system or node)
2. View version vue --version
3. Start to create the project, but first switch your cmd path to the folder where you want to create the project vue create project name
In the pop-up selection, select the third item, close the remaining eyes and enter all the way
4 cd to project name
5 npm run serve start
What to do after the empty scaffold is created?
Because there are many contents in the empty scaffold that have nothing to do with our development, we need to delete some default contents before writing our code
1. Delete helloword. In the components folder vue
2. Enter app Vue (the leader of all components. All components to be displayed in the future should be associated with app.vue. The content written in the app will be displayed everywhere)
Retain the following:
<template> <div id="app"> </div> </template> <script> export default { name: 'App', components: { } } </script> <style> </style>
Single file component
With The file at the end of vue is a single file component
In a vue file is divided into three parts. template writes HTML, script writes js, and style writes css
The data methods watch computed filters and 8 hooks we learned before have not changed except the syntax of data
Extended small concept
Component: used to encapsulate reusable ui code blocks
Module: used to encapsulate reusable js code blocks
assembly
Component: used to encapsulate reusable ui code blocks
Essence: the essence of a component is a custom label
1. Improve development efficiency
2. Reduce test difficulty
classification
Global component
Components that can be used anywhere
If you want to use
In main JS
import Vue from 'vue' import App from './App.vue' import router from './router' // 1. Global component reference import Bb from "@/components/bottombar.vue" // 2. Global component call // Vue.component("component name", the component you want to use) Vue.component("Bb",Bb) Vue.config.productionTip = false new Vue({ router, render: h => h(App) }).$mount('#app')
Then use it directly anywhere
Local component
establish
1. Create in the components folder vue end file
2. Write template script style in it (it's troublesome to write every time, so the quick creation method is to quickly generate the < V set in vscode)
<template> <div> I am a component </div> </template> <script> export default { } </script> <style> </style>
You will find that nothing is displayed because there is no relationship in the app
3. We should establish a relationship between our components and app s
(1) Quote
// 1. Reference component // import is to name the referenced content with the initial capital from "the path you referenced" import Home from "./components/home.vue" export default { name: 'App', components: { } }
(2) Call
Local components are represented by components and written at the same level as el data methods
// 1. Reference component // import is to name the referenced content with the initial capital from "the path you referenced" import Home from "./components/home.vue" export default { name: 'App', components: { // 2. Call // Component name: the component you refer to Home } }
(3) Use
<template> <div id="app"> <!-- use --> <Home/> </div> </template> <script> // 1. Reference component // import is to name the referenced content with the initial capital from "the path you referenced" import Home from "./components/home.vue" export default { name: 'App', components: { // 2. Call // Component name: the component you refer to Home } } </script> <style> </style>
Properties in components use
data methods watch computed filters properties in the eight hook components (more later)
Use of data
<template> <div> {{text}} </div> </template> <script> export default { data(){ return { text:"How are you" } } } </script> <style> </style>
reflection? Why is the data of a component a function and the original writing method is an object?
Self Baidu after class
The syntax and usage of other attributes have not changed
Style settings for components
Write styles within the style scope of the component
However, by default, the writing style of one component will affect other components. In order to solve this problem
Therefore, we need to add a scoped to the scope of the style. The current style is only effective for the current component
<style scoped> /* scoped The current style is only valid for the current component */ div{ color:red; } </style>
Parent child component
It is the nested relationship between vue components. We can easily use this nested relationship to assemble page content, so as to reduce the volume of components
Scope of parent-child components
Can the parent component directly use the data of the child component? No
Can child components directly use the data of parent components? No
Components in vue are complete and independent individuals, and their data cannot be used with each other by default
Since default does not work, is there any way?
Parent child component value transfer
Forward value transfer
The parent component sends data to the child component
props is an attribute of vue, which is written at the same level as data methods
props is used to receive data from outside components
props: ["receive parameter 1", "receive parameter 2",... "Receive parameter n"]
use:
1. Set the reception parameters of props in the sub component
export default { props:["xiaoming"],//Set receiving parameters data(){ return { zitext:"I am the data of the subcomponent" } } }
2. Insert props data into the page where you want to use it
<template> <div> <!-- use props Xiaoming data --> zizizizizizzizizizi----{{xiaoming}} </div> </template> <script> export default { props:["xiaoming"],//Set receiving parameters data(){ return { zitext:"I am the data of the subcomponent" } } } </script> <style> </style>
3. The parent component starts to transfer
Pass where the subcomponent is called
<!-- Pass data to subcomponents --> <Zi :xiaoming="futext"/>
Summarize the use of basic props
props is the attribute of the tag
props verification
This is to verify the data passed by the parent component (whether the data type is null, the default value)
props: {/ / object
}

Why is there a problem with writing, but there is no error prompt in props verification?
The production version, that is, the compressed version of the file, removes the warning, so you can see the error by using the uncompressed version of the js file
Reverse value transfer
The child component sends data to the parent component
The default is not allowed and must be passed through custom events
use:
In subcomponents:
1. Create an event and call a function in the page
2. Use this in the function$ Emit to create custom events
<template> <div> <!-- Reverse value transfer is not allowed by default. Value transfer can only be triggered by an event --> <button @click="fun()">Click me for reverse value transfer</button> </div> </template> <script> export default { data(){ return { num:"I am the data of the subcomponent!!" } }, methods:{ fun(){ // Don't record $emit as reverse value transfer. It is a self-defined event // this.$emit("name of custom event", "data you pass") this.$emit("xiaoming",this.num) } } } </script>
Parent component:
1. Use @ / v-on: custom event name where the child component is called = "function of the current parent component (no parentheses, no parentheses)"
2. Create the function of the parent component. The formal parameters in the function are the data passed by the child component
<template> <div> <h1>Reverse value transfer</h1> <!-- Function without()Function without()Function without() --> <Bzi @xiaoming="fun"/> </div> </template> <script> import Bzi from "./bzi.vue" export default { methods:{ // val is the data passed by the sub component fun(val){ console.log(val) } }, components:{ Bzi } } </script>
path alias
Built in alias
@You can see that @ is the src folder (if @ is written in any level, it is the src folder)
Custom alias
In vue scaffolding, we are provided with a folder alias of @ = src by default
But it's not enough. For example, what should we do to find the classpath of components?
to configure:
Under the root path of the project under the root path of the project under the root path of the project under the root path of the project under the root path of the project under the root path of the project
Under the root path of the project under the root path of the project under the root path of the project under the root path of the project under the root path of the project under the root path of the project
Under the root path of the project under the root path of the project under the root path of the project under the root path of the project under the root path of the project under the root path of the project
Under the root path of the project under the root path of the project under the root path of the project under the root path of the project under the root path of the project under the root path of the project
Create a Vue config. JS (the name cannot be changed)
Where you use module Exports = {} for leaks
module.exports={ configureWebpack:{ resolve:{ alias:{ // "Alias": "corresponding folder" "com":"@/components" } } } }
Don't forget to restart the project because the configuration file has been modified
slot
Slot / notch
Introduction:
Will it be displayed if I write the call of the component as a double label and write the content before bid opening and in the off label?
can't
slot usage
1. The basic usage is to place a slot component on the content component you want to accept external insertion
<template> <div> <h1>test slot</h1> <!-- An opening is set for the component, and the external content can be inserted --> <slot></slot> </div> </template> <script> export default { } </script> <style> </style>
Question:
Just now, can I insert more than one?
Pluggable
But how is it managed after inserting multiple contents into one opening?
Named notch
slot with name
When defining a slot, use the name attribute to give it a name
When inserting, use the slot attribute = "slot name" for the element
What's the use of questions?
There are similarities between slot and props
props is used when a component is called multiple times, but the content is different and the quantity is the same
slot is used when a component is called many times, but the content and quantity are different
route
A technology that can build Spa (single page application) allows our project to switch pages
Different component pages can be switched according to different URLs to achieve page switching in the user's perception
Characteristics and principles
Switch using anchor
The page will not refresh
Route creation
Scaffold automatic creation
Process: just select the Router item when vue create creates a new project
Difference from previous default scaffold items
A router folder and a views folder are added under the src folder
The router folder is the folder for configuring routes
views is the folder where routing pages are written
Create new page process
1. Create your new routing page component under views
2. Configure the index of routing rules in the router folder JS to reference the configuration
import Vue from 'vue' import VueRouter from 'vue-router' //1. All routing pages you want to use must be referenced first import Home from '../views/Home.vue' import About from '../views/About.vue' import Shop from '../views/shop.vue' Vue.use(VueRouter) //2. Configure routing rules const routes = [ { path: '/', //url matching path name: 'Home', //Namespace of the current rule (name the current route) component: Home //What is the component page I want to display when it matches }, { path: '/about', name: 'About', component: About }, { path: '/shop', name: 'Shop', component: Shop }, ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router
3. You need to create a route exit (it will be automatically added to us when it is created automatically)
The route exit is where our route will eventually be displayed
4. Set route navigation
In the traditional jump connection, we use the a tag
But don't use a tag in vue!!!!!!!
To jump to use router link is to jump to the connection of the routing page
Create manually
1. Download Vue router Library: NPM install -- save Vue router
2. Create routing component page
It's about what you create in the views folder vue file
3. Configure routing rules
Index. In the router folder JS file is referenced first in the configuration
4. Instantiate the routing object and pass in the routing rules
const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes })
5. Set the routing instance in main JS to establish a relationship in the incoming vue instance
6. Set exit router view
7. Set navigation router link
Route navigation
Route navigation is the way to switch routes
How do native html+css+js switch pages?
1.html method: a tag
2.js method: href replace() go (positive or negative) forword() back()
Routing navigation classification
1. Label method (declarative navigation): router link
Router link has a to attribute to indicate where to go
be careful:
The router link declarative navigation will eventually be compiled into a tag in the browser, but please note that we can't use a tag directly
be careful:
When we write the routing rules, the path should not be written / otherwise there will be problems in routing navigation
be careful:
router-link-active
Every time I select it, I will find that a class name will be automatically added in the route navigation. What is this class name for?
To set the currently selected style, we can set the currently selected style according to the class name dynamically added by vue
2.js mode (programming navigation)
Programming navigation is to use js to jump
Method 1: jump to the most commonly used page
this.$router.push("/ where to go")
Method 2: replace the current page (can't go back)
this.$router.replace("/ that page")
Mode 3: this$ router. The parameter of the go (n) method is an integer, which means the number of steps forward or backward in the history record, similar to window history. go(n).
Path wildcard
The * sign is used to match all paths in the path, usually to complete the creation of 404 pages
Redirection Route
Redirection is also completed through the redirect attribute configuration in routes
Priority of routing rule
The same path can match multiple routes. At this time, the matching priority is in the order of route definition: whoever defines it first will have the highest priority.
Routing mode
The hash pattern url always carries a # number. We use this pattern by default during development.
There is no # number in the url of history mode
When developing an app, there is a sharing page. The shared page is made of vue. Share this page with third-party apps. Some apps do not allow URLs with # numbers. Therefore, if you want to remove the # numbers, you need to use the history mode
After going online: 404 errors will appear when you refresh, so you need to cooperate with the back-end person to configure the url redirection of apache or nginx to redirect to your home page route.
Switching of routing mode:
In index JS, and set the mode attribute in it
const router = new VueRouter({ mode: 'history',//Setting routing mode base: process.env.BASE_URL, routes })
Nested routing / multi-level routing / two-level and three-level routing.... route
The routing syntax of level 2 and above is the same, which is configured in the routing rules using the children attribute
establish:
1. Create a multi-level routing page component
2. Configure the routing rules of the secondary route
To configure the rules of the secondary route, you must first know whose sub route it is (write the children configuration rules in whose routing rules)
Pit 1 not added/
import Vue from 'vue' import VueRouter from 'vue-router' import Home from '../views/home.vue' import Phone from '../views/phone.vue' import Shop from '../views/shop.vue' import User from '../views/user.vue' // Secondary routing import Era from '../views/er/era.vue' import Erc from '../views/er/erc.vue' import Erd from '../views/er/erd.vue' Vue.use(VueRouter) const routes = [ { path: '/home', name: 'Home', component: Home }, { path: '/phone', name: 'Phone', component: Phone }, { path: '/shop', name: 'Shop', component: Shop }, { path: '/user', name: 'User', component: User, // Configure secondary routing // Pit 1: when writing the path of the secondary route, do not add it first/ // Pit 1: when writing the path of the secondary route, do not add it first/ // Pit 1: when writing the path of the secondary route, do not add it first/ // Pit 1: when writing the path of the secondary route, do not add it first/ children:[ { path: 'era', name: 'Era', component: Era }, { path: 'erc', name: 'Erc', component: Erc }, { path: 'erd', name: 'Erd', component: Erd }, ] }, { path:"/", redirect:"/home" } ] const router = new VueRouter({ mode: 'history',//Setting routing mode base: process.env.BASE_URL, routes }) export default router
Pit 2 plus/
import Vue from 'vue' import VueRouter from 'vue-router' import Home from '../views/home.vue' import Phone from '../views/phone.vue' import Shop from '../views/shop.vue' import User from '../views/user.vue' // Secondary routing import Era from '../views/er/era.vue' import Erc from '../views/er/erc.vue' import Erd from '../views/er/erd.vue' Vue.use(VueRouter) // const routes = [ // { // path: '/home', // name: 'Home', // component: Home // }, // { // path: '/phone', // name: 'Phone', // component: Phone // }, // { // path: '/shop', // name: 'Shop', // component: Shop // }, // { // path: '/user', // name: 'User', // component: User, // //Configure secondary routing // //Pit 1: when writing the path of the secondary route, do not add it first/ // //Pit 1: when writing the path of the secondary route, do not add it first/ // //Pit 1: when writing the path of the secondary route, do not add it first/ // //Pit 1: when writing the path of the secondary route, do not add it first/ // children:[ // { // path: 'era', // name: 'Era', // component: Era // }, // { // path: 'erc', // name: 'Erc', // component: Erc // }, // { // path: 'erd', // name: 'Erd', // component: Erd // }, // ] // }, // { // path:"/", // redirect:"/home" // } // ] const routes = [ { path: '/home', name: 'Home', component: Home }, { path: '/phone', name: 'Phone', component: Phone }, { path: '/shop', name: 'Shop', component: Shop }, { path: '/user', name: 'User', component: User, // Configure secondary routing // Pit 2: add when writing the path of the secondary route/ // Pit 2: add when writing the path of the secondary route/ // Pit 2: add when writing the path of the secondary route/ // Pit 2: add when writing the path of the secondary route/ children:[ { path: '/era', name: 'Era', component: Era }, { path: '/erc', name: 'Erc', component: Erc }, { path: '/erd', name: 'Erd', component: Erd }, ] }, { path:"/", redirect:"/home" } ] const router = new VueRouter({ mode: 'history',//To set the routing mode base: process.env.BASE_URL, routes }) export default router
3. Set the exit of secondary route
By default, the exits of the primary route are automatically added by the scaffold, but the exits of the secondary route must be added manually
Use router view to write in the primary route
<template> <div> user <!-- Secondary route exit --> <router-view></router-view> <Bb/> </div> </template> <script> export default { } </script> <style> </style>
4. Route navigation
Pit 1 if the path was not added when it was created just now/
<!-- Navigation of secondary routing --> <!-- If the rules are correct path Not added/ What is the route of route navigation/Primary routing/Secondary routing --> <router-link to="/user/era">era</router-link> <router-link to="/user/erc">erc</router-link> <router-link to="/user/erd">erd</router-link>
Pit 2 if you added it when creating the path just now/
<!-- If the rules are correct path plus/ So the navigation path is /Secondary routing --> <router-link to="/era">era</router-link> <router-link to="/erc">erc</router-link> <router-link to="/erd">erd</router-link>
Dynamic routing matching routing parameters
classification
params mode
(1) Set the acceptance parameter in the routing rule that needs to accept data: xxx
{ path: '/shopall/:Write casually', //Set acceptance parameters name: 'Shopall', component: Shopall },
(2) Start delivery
Declarative delivery
<!-- <router-link :to="{name:'The name of the route you're going to',params:{Parameter 1 you bind on the rule: value, parameter you bind on the rule n: value}}">params Declarative parameter passing</router-link> --> <router-link :to="{name:'Shopall',params:{xiaoming:'I'm passing past arguments params'}}">params Declarative parameter passing</router-link>
Programming method transfer
Try and add notes after class
(3) Accept parameters
this.$route.params.xxx
<!-- Accept the passed data --> {{this.$route.params.xiaoming}}
query mode
The query method does not need to configure parameters in the routing rules
The query method does not need to configure parameters in the routing rules
The query method does not need to configure parameters in the routing rules
The query method does not need to configure parameters in the routing rules
query mode does not need to configure parameters in routing rules
(1) Send data
Programming mode
<template> <div> phone <button @click="fun()">Point I use query Transfer parameters</button> <Bb/> </div> </template> <script> export default { methods:{ fun(){ // The programming method of parameter transfer is the same as that of declaration this.$router.push({name:"Phoneall",query:{xiaohong:"I am query Chuan Shen ha"}}) } } } </script> <style> </style>
Try and take notes by yourself after class in a declarative way
(2) Receive data
this.$route.query.xxx
The difference between query and params
1. Usage: query should be imported with path and params should be imported with name. The receiving parameters are similar, which are this r o u t e . q u e r y . n a m e and t h i s . route.query.name and this route.query.name and this route. params. name.
2.url display
query is key=val params on the url display, and only val on the url display
Because the key can be displayed in query mode, it is not so safe in data transmission. panams is relatively safe
Route guard / route guard / route hook / route verification
These are hook functions that are triggered automatically when vue routes jump
Global guard
For all routes, it takes effect when switching
Global front guard
Triggered before entering the route
When a navigation is triggered, the global front guard (before entering the component) is called in the order of creation.
Router provided by Vue router Before each ((to, from, next) = > {}) can easily realize global front navigation
To: the target routing object to be entered
from: the route that the current navigation is about to leave
Next: next execution
// Global guard // to: where // From: where do you come from // Next: next router.beforeEach((to,from,next)=>{ console.log(to) console.log(from) if(to.path=="/login"||to.path=="/zhuce"){ next() }else{ alert("You are not logged in. Please log in and try again") next(false) } })
Global post guard
Triggered after entering the route
When a navigation is triggered, the global post hook (after entering the component) is called.
Router provided by Vue router After each ((to, from) = > {}) implements global post guard
To: the destination routing object to be entered
from: the route that the current navigation is about to leave
Route exclusive guard
Effective only for the current one
Compared with the global front guard, the route exclusive guard only controls the current route with the same parameters as the global front guard
Define beforeEnter directly on the route configuration to define the route exclusive guard
{ path: '/', name: 'Home', component: Home, // Route exclusive beforeEnter(to,from,next){ alert("Currently vip Please log in and visit the page") next("/login") } },
Guard in assembly
In component guard is triggered when switching routes for a self-defined component range
Before entering
beforeRouteEnter(to, from, next) {} to enter the hook before the build
When I left
Use beforeRouteLeave(to, from, next) {} in the component to hook out of the component
<template> <div> user </div> </template> <script> export default{ // Triggered by leaving in the component of routing guard beforeRouteLeave(to,from,next){ if(confirm("Are you sure to leave?*_!")){ // Normal departure next() }else{ // Can't leave next(false) } } } </script> <style> </style>
Route lazy loading
Because Vue router is a single page application (that is, there is only one display page, and the rest of the content is switched according to the url in which display page to switch the routing page component)
By default, vue will load all the routing pages we wrote when loading for the first time, which is not a big problem. However, once there are more pages (many pages need to be loaded when loading for the first time, it may cause the problem of browser white screen / slow loading of the first screen)
Solution: use routing lazy loading
use
Must master the way
import mode
import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter) const routes = [ // Lazy loading mode { path: '/home', name: 'home', component: () => import('../views/home.vue') }, { path: '/phone', name: 'phone', component: () => import('../views/phone.vue') }, { path: '/shop', name: 'shop', component: () => import('../views/shop.vue') }, { path: '/user', name: 'user', component: () => import('../views/user.vue') } ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router
How to understand asynchronous components
{ path: '/shop', name: 'shop', component: resolve=>(require(["Referenced component path"],resolve)) },
Expand small knowledge - how to start the scaffold project?
After going to the company, the startup methods of each project may be different, so we need to check what commands are used to start the project
Under the root path of the project, under the root path, under the root path, under the root path, view the package JSON file to find the scripts node to know how to start
axios and interceptor encapsulation
Basic writing method (it is not recommended to use too low company, but it is not recommended to use too low company)
1. Download axios npm install --save axios
2. To use import axios from "axios"
Interceptor
-
request interceptor
The function of the request interceptor is to perform some operations before the request is sent. For example, a token is added to each request body for unified processing. It is also very easy to change it in the future. -
Response interceptor
The function of the response interceptor is to perform some operations after receiving the response. For example, when the server returns to the login status and fails and needs to log in again, jump to the login page.
establish
1. Create a util folder (that is, the folder where some tool libraries are stored) and an api folder
2. Create the interceptor file and write the interceptor content
import axios from "axios" // Create axios and assign it to the constant service const service = axios.create(); // Add request Interceptors service.interceptors.request.use(function (config) { // What to write before sending the request return config; }, function (error) { // What to do when the request is wrong return Promise.reject(error); }); // Add response interceptor service.interceptors.response.use(function (response) { // Do something about the response data return response; }, function (error) { // Do something about response errors return Promise.reject(error); }); export default service
3. Encapsulate data requests
// Encapsulate data requests // Reference interceptor import service from "@/util/request.js" // 2. Start encapsulation request export function getlink(url){ return new Promise((resolve,reject)=>{ service.request({ // How to write the original axios? Write it now url, method:"GET" }).then((ok)=>{ resolve(ok) }).catch((err)=>{ reject(err) }) }) }
4 page usage
Analog data mockjs
mockjs is used to create an analog data interface in vue. When we don't give us an interface in the background, our project becomes a dynamic request
1. Download: npm install --save mockjs
2. If we want to have simulation data in the project, where do we need to write it----- Create a mock folder to hold simulation data
3. Create a data folder under the mock folder to hold the simulation data and create a js file to write mockjs code
import Mock from "mockjs" // Create first request Pay attention to case get Lower case // Mock.mock("write the request address yourself", "get/post",require("the address of your simulation data json")) Mock.mock("/xiaoming/xiaohong","get",require("./data/demo.json"))
4.mock also needs to be referenced in the configuration file. Don't forget
mock also needs to be referenced in the configuration file. Don't forget
mock also needs to be referenced in the configuration file. Don't forget
mock also needs to be referenced in the configuration file. Don't forget
mock also needs to be referenced in the configuration file. Don't forget
mock also needs to be referenced in the configuration file. Don't forget
mock also needs to be referenced in the configuration file. Don't forget
mock also needs to be referenced in the configuration file. Don't forget
mock also needs to be referenced in the configuration file. Don't forget
In main JS
import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store' require("./mock")//Reference mock Vue.config.productionTip = false new Vue({ router, store, render: h => h(App) }).$mount('#app')
Background sending parameters
rest api is a best practice of separating front end and back end. It is a set of standards or specifications for development, not a framework.
Norm: I tell you what to do, but if you don't follow me, there may be no problem, but if there is a problem, don't come to me
Rule: if I tell you what to do, you have to do it. If you don't do what I say, it's over
Rest API is to set a more semantic name for the interface when defining the interface
GET get data
POST send data
DELETE delete
Update / modify
PUT more means to modify all or some
PATCH is more about modifying a
How to send parameters to the background
When sending parameters, in fact, 70% of the cases can be written as follows
GET
http://localhost:3000/ceshi/get
The request parameter is name
params is used to pass parameters
import service from "@/util/service.js" export function getlink(url,params){ return new Promise((resolve,reject)=>{ service.request({ url, method:"GET", // get sends data using params params }).then((ok)=>{ resolve(ok) }).catch((err)=>{ reject(err) }) }) }
DELETE
http://localhost:3000/ceshi/delete
Parameter delid
Just modify the sending method the same as get
PUT
http://localhost:3000/ceshi/put
Parameter putid
Just modify the sending method the same as get
POST
http://localhost:3000/ceshi/post
Parameter postid
Data is used to send data when post sends data
import service from "@/util/service.js" export function postlink(url,data){ return new Promise((resolve,reject)=>{ service.request({ url, method:"POST", // Data is used to send data when post sends data data }).then((ok)=>{ resolve(ok) }).catch((err)=>{ reject(err) }) }) }
mounted(){ // When sending parameters through post, there is no way to send them directly, because they are not available by default // Method analysis // So we need to set the post parameter and parse the parameter let usp=new URLSearchParams() // usp.append("key you sent", "val you sent") usp.append("postid",9999) postlink("/api/ceshi/post",usp).then((ok)=>{ console.log(ok) }) }
Solve cross domain
jsonp
Forward proxy
You must create a vue under the root path of the vue config. JS file
Write the following configuration in it
module.exports={ // Configure cross domain devServer: { proxy: { //Configure cross domain '/api': { target: 'http://localhost:3000 / ', / / the background address here is simulated; You should fill in your real background interface changOrigin: true, //Allow cross domain pathRewrite: { '^/api': '' } }, } }, }
Modify the request address to / api/xxxx. Note that the project must be restarted after the configured agent
cors
Interceptors are more configured to be used with the front end of token
1. More interceptor configurations - corresponding interception
The status (status code) of the failed response needs to get error in the response response. status
// Add response interceptor service.interceptors.response.use(function (response) { // Do something about the response data - the place where the background can normally intercept the corresponding data return response; }, function (error) { // Do something about the response error - where 404 500 403 appears console.log(error.response.status) switch (error.response.status) { case 500: // Processing operations alert("Current connection timed out") break; case 404: // Processing operation alert("The page you visited does not exist") // Jump to the first page break; default: return Promise.reject(error); } return Promise.reject(error); });
Extended knowledge - automatically open browser and port modification
First create Vue. Exe under the root path of the project config. js
module.exports={ devServer:{ port:8899// Modify port } }
Automatically open browser
module.exports={ devServer:{ port:8899,// Modify port open:true//Automatically open browser } }
Dynamic component
Let multiple components use the same mount point and switch dynamically, which is dynamic component.
<template> <div class="about"> <h1>Dynamic component</h1> <!-- 2.Using dynamic components --> <!-- 4.insert --> <button @click="tem='Taba'">teba</button> <button @click="tem='Tabb'">tebb</button> <button @click="tem='Tabc'">tebc</button> <component :is="tem"></component> </div> </template> <script> // 1. You can only use it by importing all the components you want to set up dynamic components import Taba from "@/components/taba.vue" import Tabb from "@/components/tabb.vue" import Tabc from "@/components/tabc.vue" export default { // 3. Create variables used by dynamic components data(){ return { tem:Tabc } }, components:{ Taba,Tabb,Tabc } } </script>
Keep alive -- resolve state loss
In the last demo, when we kept switching the contents of the two tabs, we found that the selected contents in the exercise will resume initialization after switching routes.
That is, the previous state is lost. The reason is that Vue creates a new component instance every time it switches routes
keepalive is to solve the problem of state loss
use
If you want to use it, use the keep Alice package at the exit where you want to save the component state
To solve this problem, we can wrap the route exit with an element. During the switching process, the state is kept in memory to prevent repeated rendering of DOM, reduce loading time and performance consumption, and improve user experience
Use on dynamic components <keep-alive> <component :is="tem"></component> </keep-alive> Use on Routing <keep-alive> <router-view/> </keep-alive>
Properties of dynamic components
For example, just now we have three dynamic components. If I wrap the dynamic components, they will save the state of all three components
What if I point to saving two of the three dynamic components and not saving one?
Who does include need to cache
<!-- Point to cache a and c Two components --> <keep-alive include="Taba,Tabc"> <component :is="tem"></component> </keep-alive>
exclude who doesn't want to cache
be careful
If both attributes are written, exclude takes precedence over include
Keep alive hook function
These two lifecycle functions must be based on the use of keep alive components.
Activated type: func trigger timing: used when keep alive components are activated;
Deactivated type: func trigger timing: called when a keep alive component is deactivated;
Custom instruction
In addition to built-in instructions, user-defined instructions
Local instruction definition:
directives:{
Name of custom instruction:{
Custom instruction hook function (el){
Operation logic
}
}
},
Custom instruction hook function
Bind: bind an instruction to an element and execute it only once
Inserted: the hook function is basically operated when the instruction bound element is inserted into the page for display
update: called when all component nodes are updated
componentUpdated: the node and its child nodes of the instruction component are updated after completion.
unbind: unbinds an instruction from an element and executes it only once
<template> <div> <h1>Custom instruction</h1> <!-- How to use custom instructions? --> <!-- The essence of an instruction is the attribute of an element --> <input type="text" v-xiaoming> <h1 v-red>I am testing custom specified elements</h1> </div> </template> <script> export default { directives:{ // Name of custom instruction:{ // el is bound to that element. Who is this el // Custom instruction hook function (el){ // Operation logic // } // } xiaoming:{ inserted(el){ // focus() gets the focus by itself el.focus() } }, red:{ inserted(el){ el.style.color="red"; } } } } </script> <style> </style>
ref
Think about documet, which can use js in vue Does getelementbyxxxx perform dom operation?
have access to
mounted(){ console.log(document.getElementsByTagName("p")[0].innerHTML) }
Think 2 can jquery be used for dom operations in vue?
have access to
1. Download npm install --save jquery\
2. Reference import $from "jquery"
3,. use
Why ref
Although it is not recommended in vue, it is not recommended to use dom operation
In some extreme cases, it has to be used, so in vue, we use ref to perform dom operations in vue
use
ref is to name the dom element in vue
<em ref="demoem">I'm testing vue of ref Examples of</em>
r e f s this individual Just mutually When to d o m check look for t h i s . refs is equivalent to dom searching this Refs is equivalent to dom searching this refs. The ref name you gave dom
funb(){ this.$refs.demoem.style.color="pink"; }
Location of ref binding
ref is bound to the dom element
You can perform dom operations on the page
ref is bound to sub components
By binding to a component, you can get all the properties and methods of the component
Could you tell me how a parent component in vue can trigger a child component?
vuex
It is mainly used for component value transmission
Forward value props
Reverse value transfer $emit()
Sibling value transfer (later)
Kua level / Kua component value transfer - vuex
Traditional cross level value transfer
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-suy35PGQ-1624408588812)(.\img.bmp)]
The news component uses the data of the contact component to pass through several forward and reverse transmissions in the traditional way, and the maintainability in the later stage is 0
The simple method is similar to cross level value transfer
VUEX basic
vuex status (data) management tool
Vuex is a data warehouse. All component data are uniformly placed in vuex. In this way, if the component wants to use data, the component can directly read it in vuex, which greatly simplifies the complexity of data transmission
vuex's centralized data storage facilitates access to all components in the program
Create vuex
Automatic creation method
Select vuex when creating vue scaffold
Create manually (remember)
1. Download vuex npm install --save vuex
2. Create folders and files
3. Start creating the store (the variable stores the vuex instance)
import Vue from 'vue'//Reference vue import Vuex from 'vuex' //Reference vuex Vue.use(Vuex)// Use vuex in vue // Expose vuex instances export default new Vuex.Store({ })
4 inject vuex instance reference into vue instance
import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store'//Reference vuex instance Vue.config.productionTip = false new Vue({ router, store,//Inject vuex into the vue instance for use render: h => h(App) }).$mount('#app')
Five core API s of vuex
state - data source
The function of state is not complicated, but all data of vuex used to create data must only be placed in state
establish
import Vue from 'vue'//Reference vue import Vuex from 'vuex' //Reference vuex Vue.use(Vuex)// Use vuex in vue // Expose vuex instances export default new Vuex.Store({ state:{//Data storage can store any data text:"I am a string", num:123, arr:[1111,2222,3333,444,5555] } })
Use data state
In the component where you want to use data, this$ store. state. XXX uses vuex's state data
<template> <div class="about"> <h1>This is an about page</h1> <h1>{{this.$store.state.text}}</h1> </div> </template>
The data stored in the state is responsive. Vue components read data from the store. If the data in the store changes, the components that depend on the data will also be updated
vuex's data is responsive, so since we want to be responsive, how can we modify it?
mutations
Changes modifies vuex's state data. It has only one function: modifying
Changes is a property, and its inner side is a method to modify state.
establish
import Vue from 'vue'//Reference vue import Vuex from 'vuex' //Reference vuex Vue.use(Vuex)// Use vuex in vue // Expose vuex instances export default new Vuex.Store({ state:{//Data storage can store any data text:"I am a string", num:123, arr:[1111,2222,3333,444,5555] } , mutations:{//Modify state data // Modify method 1 (the formal parameter state is the state above) {}, // Modify method 2 (the formal parameter state is the state above) {}, // Modify method 3 (the formal parameter state is the state above) {}, // Modify method 4 (the formal parameter state is the state above) {}, // Modify method 5 (the formal parameter state is the state above) {}, xiaoming(state){ state.text="ha-ha" } } })
A modified mutation is created above
Although there is a xiaoming modification method, how can I call it in the component page?
Call the modified method commit("called method name") in mutatioins
<template> <div class="about"> <h1>This is an about page</h1> <h1>{{this.$store.state.text}}</h1> <button @click="fun()">Click me to modify</button> </div> </template> <script> export default { methods:{ fun(){ // Call modify call modify use this$ store. Commit ("method name of changes") this.$store.commit("xiaoming") } } } </script>
vuex mutations submit load payload
xiaoming(state,payload){ state.text=payload.name } Call in component this.$store.commit("xiaoming",{key:val,key:val})
Extension ----- it is important to know that vuex data refresh is lost
<template> <div class="about"> <h1>This is an about page</h1> <h1>{{this.$store.state.text}}</h1> <button @click="fun()">Click me to modify</button> </div> </template> <script> export default { // Solve the problem of vuex data refresh loss created () { //Read the status information in localStorage when the page is loaded if (localStorage.getItem("data") ) { //replaceState replaces the data object Assign merge objects this.$store.replaceState(Object.assign({}, this.$store.state,JSON.parse(localStorage.getItem("data")))) } //Save the information in vuex to localStorage when the page is refreshed window.addEventListener("beforeunload",()=>{ localStorage.setItem("data",JSON.stringify(this.$store.state)) }) }, // Solve the problem of vuex data refresh loss methods:{ fun(){ // Call modify call modify use this$ store. Commit ("method name of changes") this.$store.commit("xiaoming") } } } </script>
actions handles asynchronous operations
The only role of actions in vuex is to handle asynchronous operations
actions is an attribute of vuex. It writes methods one by one. Asynchronous operations are stored in the methods
establish
import Vue from 'vue'//Reference vue import Vuex from 'vuex' //Reference vuex Vue.use(Vuex)// Use vuex in vue // Expose vuex instances export default new Vuex.Store({ state:{//Data storage can store any data text:"I am a string", num:123, arr:[1111,2222,3333,444,5555] } , mutations:{//Modify state data // Modify method 1 (the formal parameter state is the state above) {}, // Modify method 2 (the formal parameter state is the state above) {}, // Modify method 3 (the formal parameter state is the state above) {}, // Modify method 4 (the formal parameter state is the state above) {}, // Modify method 5 (the formal parameter state is the state above) {}, xiaoming(state,payload){ state.text=payload.name } }, actions:{//Handling asynchronous operations // One by one demoa(){console.log("I was the first asynchronous")}, demob(){console.log("I'm the second asynchronous")}, democ(){console.log("I'm the third asynchronous")}, } })
Call actions if actions wants to be called, you must use this$ store. Dispatch ("actions name")
<template> <div class="home"> <img alt="Vue logo" src="../assets/logo.png"> <h1>{{this.$store.state.text}}</h1> <button @click="fun()">Click my settings payload</button> <button @click="funb()">Click me to call asynchronous operation</button> </div> </template> <script> export default { name: 'Home', methods:{ fun(){ // If you want to pass more than one object, just pass one object for a long time this.$store.commit("xiaoming",{name:"xixi",age:18}) }, funb(){ this.$store.dispatch("demoa") } }, components: { } } </script>
actions for vue asynchronous request data closed loop
1. Since you want to make asynchronous requests, you need to use axios in vue to create util and api to encapsulate requests and interceptors
2. asynchronous operation is in vuex actions, so we need to create a method in actions to call asynchronous requests in the method.
import Vue from 'vue' import Vuex from 'vuex' // quote import {getlink} from "@/api/getapi.js" Vue.use(Vuex) export default new Vuex.Store({ state: { }, mutations: { }, actions: { // Asynchronous operations need to be sent in vuex actiondemoa(){ getlink("http://api.artgoer.cn:8084/artgoer/api/v1/user/324380/v3/topic/topicHomeByLabel?pageIndex=1&token=b544cd63-6d42-46fe-a96c-3cf96bae3113&topicId=62187").then((ok)=>{ console.log(ok) }) } } }, modules: { } })
3. Trigger actions (this.$stroe.dispatch()) in the component page that needs to send the request, and then the request will be sent
<template> <div class="hello"> <h1>{{ msg }}</h1> </div> </template> <script> export default { name: 'HelloWorld', mounted(){ // Because the asynchronous request is in the actions of vuex, I need to call actions this.$store.dispatch("actiondemoa") }, props: { msg: String } } </script> </style>
4. The data has been printed out in actions. Because the data of vuex needs to be stored in state, we need to ask actions to request data to modify a variable in state
In actions, call commit to trigger changes and modify state
import Vue from 'vue' import Vuex from 'vuex' // quote import {getlink} from "@/api/getapi.js" Vue.use(Vuex) export default new Vuex.Store({ state: { arr:[] }, mutations: { dataarr(state,payload){ state.arr=payload } }, actions: { // Asynchronous operations need to be sent in vuex actiondemoa(context){ getlink("http://api.artgoer.cn:8084/artgoer/api/v1/user/324380/v3/topic/topicHomeByLabel?pageIndex=1&token=b544cd63-6d42-46fe-a96c-3cf96bae3113&topicId=62187").then((ok)=>{ console.log(ok.data.data.commentList) // Submit the requested data to changes for modification context.commit("dataarr",ok.data.data.commentList) }) } }, modules: { } })
Use on page
Closed loop diagram of data request
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-Tvyxcki2-1624408588814)(.\img.png)]
payload
acions can also pass parameters to actions through dispatch, and this parameter is payload
getters
getters is the computed property of vuex
What is the difference between the getters of vuex and the computed calculation attribute of traditional vue?
The data processed by the calculation attribute of the scope vue can only be used in the current component, but the data processed by vuex using getters can be used multiple times in any component
When a piece of data shows different forms in a component, the calculation attribute of vue is used
When a piece of data wants to reuse the processed data of different forms in multiple components, use vuex getters
getters is a property of vuex
establish:
getters:{//Calculated properties of vuex newtext(state){ return state.text.toUpperCase() } },
use
The same as using state, use this in the calculated properties in the component$ store. getters. XXX to call
modules
In Vue, the state uses a single state tree structure, and all States should be placed in the state. If the project is complex, the state is a large object, and the store object will become very large and difficult to manage.
Module: each module can have its own state, mutation, action and getters, making the structure very clear and convenient for management.
1. Create a new folder storage module in the store folder
2. Write modules belonging to components
export let aboutm={ state: { demoa:"111", demob:"22", democ:"113331", }, mutations: { }, actions: { }, }
3. Reference in vuex configuration
import Vue from 'vue' import Vuex from 'vuex' import {aboutm} from "./modules/aboutm.js" import {homem} from "./modules/homem.js" Vue.use(Vuex) export default new Vuex.Store({ modules: { aboutm,homem } })
4 note that if a module is used, there will be a difference when reading data
this.$store.state. Module name xxxx
vantui
https://vant-contrib.gitee.io/vant/#/zh-CN/
Component value transfer
Forward value props
Reverse value transfer $emit() ref
Sibling value passing eventBus
Central event bus eventBus
After creating a new Vue instance, it will act as a bridge for communication between components, that is, the central event bus.
1. Create a new folder to hold the vue instance of the central event bus
// The central event bus is a new vue instance used as a data bridge for sibling components import Vue from "vue" export default new Vue()
2. When brothers transfer values, demoa needs to send data to demob
(1) Now use $emit() in demo a to bind data to that vue instance through custom events\
<template> <div> assembly a <button @click="fun()">I'll pass the data to my brother demob</button> </div> </template> <script> // 1. Reference central time bus import eventbus from "@/eventbus" export default { data(){ return { text:"I am demoa Variables inside" } }, methods:{ fun(){ // 2. Directly bind custom events to the imported central time bus in the event eventbus.$emit("apao",this.text) } } } </script> <style> </style>
(2) Use $on in demob to listen for custom events on the receiving instance
<template> <div> assembly b </div> </template> <script> // 1. Reference central time bus import eventbus from "@/eventbus" export default { // 2. Let's start listening mounted(){ eventbus.$on("apao",(val)=>{ console.log(val) }) } } </script> <style> </style>
1. Create an event bus, such as eventBus in demo, and use it as a communication bridge
2. Use bus in components that need to transfer values
e
m
i
t
touch
hair
one
individual
since
set
righteousness
matter
piece
,
and
pass
Deliver
ginseng
number
(
e
m
i
t
front
plus
beautiful
element
symbol
)
3
,
stay
need
want
meet
collect
number
according to
of
group
piece
in
use
b
u
s
.
Emit triggers a custom event and passes parameters (insert dollar sign before emit). 3. Use bus in the component that needs to receive data
Emit triggers a user-defined event and passes parameters (the dollar sign is added before emit). 3. Use bus in the component that needs to receive data On listens to custom events and processes the passed parameters in the callback function
Cross component value passing vuex
Mixins mixed in
mixins is a component reuse technology in vue. It can extract many of the same attributes and methods in components to facilitate the reuse of multiple components
Local mixing
1. Create a folder to hold the mixed content
let mixinsdemo={ methods:{ funb(){ console.log("I am a method") } }, data(){ return { textm:"I'm a mixed variable" } } } export default mixinsdemo
2. Reference and call where you want to use it
<template> <div> assembly a <button @click="funb()">Click me to call the mixed method---{{textm}}</button> </div> </template> <script> // Reference blending import mixinsdemo from "@/mixins" export default { // Call mixins mixins:[mixinsdemo], } </script> <style> </style>
Global blending
Can be used in any component
Reference and use in main
import MinXin from '@/components/MinXins/index.js'
Vue.mixin(MinXin);
You can freely use the mixed data in the component
Route splitting - independent of the outline content (understand and master)
1. The index file under router will lead to difficulties in later maintenance as the project volume gradually increases
elementui
See the official website for details https://element.faas.ele.me/#/zh-CN/component/quickstart
quote
main.js Add in import ElementUI from 'element-ui'; import 'element-ui/lib/theme-chalk/index.css'; Vue.use(ElementUI);