Vue2
1. Basic use
- Understanding of SPA applications
- Single Page Web Application (SPA).
- The entire application has only one complete page.
- Clicking on a navigation link in a page does not refresh the page, only a partial update of the page.
- The data needs to be retrieved through ajax requests.
1. Meet the vue
- 1. For Vue to work, you must create an instance of Vue and pass in a configuration object.
- 2. The code in the root container is still HTML compliant, but with some special Vue syntax mixed in.
- 3. The code in the root container is called the Vue template.
- 4.Vue instances and containers are one-to-one;
- 5. There is only one Vue instance in real development, and it will be used with components;
- 6. {{XXX}} in the expression to write js, XXX and XXX can be read automatically – to all attributes of the data;
- 7. Once the data in the data is changed, the page where the data is used is automatically updated;
Note the distinction between: JS expressions and JS code (statements)1.Expression: An expression produces a value, which can be placed wherever a value is needed:1). a
(2). a+b
(3). demo(1)
(4). x === y ? 'a' : 'b'
2.Js code (statement) (1). if() {} (2). for() {}3.Create the HTML outermost container <div id="#root"></div>
4.Create vUE real columnsnew Vue({
el:"#root".//el specifies which container is served by the current Vue instance. The value is usually a CSS selector string.
data: {name:'Hi' //data is used to store data for use by containers specified by el}})Copy the code
2. Template syntax
- 1. Interpolation syntax:
- Function: Used to parse label body content.
- {{XXX}}, XXX is a JS expression, and can read all attributes in data directly
- 2. Instruction syntax:
- Function: Used to parse tags (including tag attributes, tag body contents, and binding events…..) .
- For example: v-bind:href=” XXX “or abbreviation :href=” XXX”, XXX also needs to write js expressions,
- And all properties in data can be read directly.
- Note: There are many instructions in Vue, and they are all in the form of: V-???? We’re just using V-bind here as an example.
<a v-bind:href="school.url.toUpperCase()" x="hello"{{school. Name}} </a><a :href="school.url" x="hello">{{school. Name}} 2</a>
Copy the code
3. Data binding
- There are two ways to bind data in Vue:
- 1. V-bind: Data can only flow from data to the page.
- 2. Two-way binding (V-model) : Data can flow not only from data to pages, but also from pages to data.
- Remark:
- 1. Bidirectional binding is usually applied to form elements (input, SELECT, etc.)
- 2. V-model: Value can be shortened to V-model because v-model collects value values by default.
4.. Two ways of writing EL and data
- Two ways of writing el
Vue.config.productionTip = false // Prevents vUE from generating production prompts at startup.
const v = new Vue({
//el:'#root', //
data: {name:'Hi'
}
})
v.$mount('#root') // */
Copy the code
5. MVVM model
-
The MVVM model
-
- M: Model: data in data
-
- V: View: template code
-
- VM: ViewModel: Vue instance
-
-
Observations:
- 1. All attributes in data finally appear on vm.
- 2. All attributes on the VM and all attributes on the Vue prototype can be directly used in the Vue template.
6. Data broker
Object.defineProperty
-
1. Data broker in Vue:
- Proxy operations (read/write) on properties in data objects through VM objects
-
2. Benefits of data broker in Vue:
- More convenient operation of data in data
-
3. Basic Principles:
- Add all attributes from the data Object to the VM via Object.defineProperty().
- Specify a getter/setter for each property added to the VM.
- To manipulate (read/write) the corresponding property in data inside the getter/setter.
let number = 18
let person = {
name:'Joe'.sex:'male',}Object.defineProperty(person,'age', {// value:18,
// Enumerable :true, // Controls whether an attribute can be enumerable, the default is false
// writable:true, // Controls whether properties can be modified. The default value is false
// The control attribute can be deleted without any additional information. The default value is false
// When someone reads the age property of person, the getter is called and the value returned is the age value
get(){
console.log('Someone read the age property')
return number
},
// When someone modifies the age property of Person, the set function (setter) is called and the modified value is received
set(value){
console.log('Someone changed the age property and the value is',value)
number = value
}
})
// console.log(Object.keys(person))
console.log(person)
// name: "zhang SAN"
// sex: "male"
// age: 18
ƒ get()
// set age: ƒ set(value)
/ /.. proto.. : Object
Copy the code
7. Event handling
1. Basic use of events
- 1. Use V-on: XXX or @xxx(short) to bind events, where XXX is the event name.
- 2. Event callback needs to be configured in the Methods object, which will eventually be on the VM;
- 3. Do not use arrow functions configured in methods. Otherwise this would not be vm;
- 4. Functions configured in Methods are all functions managed by Vue. This refers to vm or component instance object.
- 5.@click=”demo” and @click=”demo($event)”;
<button @click="showInfo1"> click my prompt message1</button><button @click="showInfo2($event,66)">Click my prompt message 2 (Pass parameters)</button>
showInfo1(event){
alert('event',event)
},
showInfo2(event,number){
console.log(event,number)
// console.log(event.target.innerText)
alert('showInfo2')}Copy the code
2. Event modifiers
- 1. Prevent: prevent default events.
- 2. Stop: Prevent events from bubbling.
- 3. Once: The event is triggered only once (common).
- 4. Capture: Use the event capture mode;
- 5. Self: Fires the event only if event.target is an element of the current operation;
- 6. Passive: The default action of the event is executed immediately without waiting for the event callback to complete.
<! -- Prevent default events --><a href="http://www.baidu.com" @click.prevent="showInfo">Click my prompt message</a><! -- Prevent events from bubbling (common) --><div class="demo1" @click="showInfo">
<button @click.stop="showInfo">Click my prompt message</button>
<! -- modifiers can be written consecutively -->
<! - < a href = "http://www.baidu.com" @ click. Prevent. Stop = "showInfo" > me message < / a > -- >
</div><! -- Event only fires once --><button @click.once="showInfo">Click my prompt message</button><! -- Use event capture mode --><div class="box1" @click.capture="showMsg(1)">
div1
<div class="box2" @click="showMsg(2)">
div2
</div>
</div>
// vue.config.keycodes. custom key name = key code, you can customize key alias
<input type="text" placeholder="Press Enter for input." @keydown.enter="showInfo">Vue. Config. KeyCodes. Enter = 13 / / defines an alias buttonsCopy the code
8. Computed attributes (computed)
- 1. Definition: The attribute to be used does not exist, and must be calculated from the existing attribute.
- 2. Rationale: The underlying getters and setters provided by objcet.defineProperty methods are used.
- 3. When is the get function executed?
- (1). It will be executed once for the first read.
- (2). It will be called again when the dependent data changes.
- 4. Advantages: Compared with methods implementation, internal cache mechanism (reuse), higher efficiency (call only when the value changes), convenient debugging.
- 5. Note:
- 1. Calculated attributes will eventually appear on the VM and can be directly read and used.
- 2. If the calculated property is to be modified, the set function must be written in response to the modification, and the set function to cause the data dependent on the calculation to change.
computed: {fullName: {// What does get do? When someone reads the fullName, get is called and the return value is the fullName value
// When is get called? 1. Read fullName for the first time. 2. When the dependent data changes.
get(){
console.log('Get is called')
// console.log(this) // where this is vm
return this.firstName + The '-' + this.lastName
},
// When is set called? When the fullName is modified.
set(value){
console.log('set',value)
const arr = value.split(The '-')
this.firstName = arr[0]
this.lastName = arr[1]}},/ / short
fullName(){
console.log('Get is called')
return this.firstName + The '-' + this.lastName
}
}
Copy the code
9. Monitoring Properties (Watch)
-
1. When the monitored attribute changes, the callback function is automatically invoked to perform related operations
-
2. Monitoring properties must exist in order to monitor!!
-
Deep monitoring:
- (1). In the Vue
Watch does not monitor changes in object internal values by default (layer 1)
. - (2). The configuration
Deep :true can detect internal value changes of objects (multiple layers)
.
- (1). In the Vue
-
Remark:
- (1).Vue itself can monitor the change of the internal value of the object, but the watch provided by Vue cannot by default!
- (2) When using Watch, decide whether to adopt deep monitoring according to the specific structure of data.
-
Differences between computed and Watch:
- Watch can complete all the functions that 1.computed can complete.
- 2. Functions that can be performed by watch may not be performed by computed. For example, watch can perform asynchronous operations.
watch: {isHot: {immediate:true.// Let handler call it when initializing
// When is the handler called? When isHot changes.
// params (new value, old value)
handler(newValue,oldValue){
console.log('isHot has been modified ',newValue,oldValue)
}
},
/ / short
isHot(newValue,oldValue){
console.log('isHot has been modified ',newValue,oldValue,this)},numbers: {deep:true.handler(){
console.log('Numbers have changed')}},//
vm.$watch('isHot', {immediate:true.// Let handler call it when initializing
deep:true.// Deep monitoring
handler(newValue,oldValue){
console.log('isHot has been modified ',newValue,oldValue)
}
}),
/ / short
vm.$watch('isHot'.(newValue,oldValue) = >{
console.log('isHot has been modified ',newValue,oldValue,this)})}Copy the code
10. Binding styles
1. The style of the class
- Class =” XXX “XXX can be a string, an object, or an array.
- The string notation is suitable for: class names are uncertain and need to be retrieved dynamically.
- Object writing is useful for binding multiple styles with an indeterminate number of names.
- Array notation is useful for binding multiple styles with a certain number of styles and a certain name, but not a certain use.
2. Style style
- :style=”{fontSize: XXX}”
- :style=”[a,b]”
<! - bindingclassStyle -- string writing, suitable for: style class name is indeterminate, need to be specified dynamically --> <div class="basic" :class="mood" @click="changeMood">{{name}}</div> <br/><br/><! - bindingclassStyle -- Array writing, suitable for: the number of styles to bind is not determined, the name is not determined --> <div class="basic" :class="classArr">{{name}}</div> <br/><br/><! - bindingclassStyle -- object writing, suitable for: the number of styles to bind, the name is also determined, but to dynamically decide whether to use --> <div class="basic" :class="classObj">{{name}}</div> <br/><br/><! > < span style = "box-sizing: border-box! Important; word-wrap: break-word! Important;<div class="basic" :style="styleObj">{{name}}</div> <br/><br/><! -- Bind style -- array style --><div class="basic" :style="styleArr">{{name}}</div>
const vm = new Vue({
el:'#root'.data: {name:'ClassDemo'.mood:'normal'.classArr: ['claname1'.'claname2'.'claname3'].classObj: {claname1:false.claname2:false,},styleObj: {fontSize: '40px'.color:'red',},styleObj2: {backgroundColor:'orange'
},
styleArr:[
{
fontSize: '40px'.color:'blue'}, {backgroundColor:'gray'}},methods: {
changeMood(){
const arr = ['happy'.'sad'.'normal']
const index = Math.floor(Math.random()*3)
this.mood = arr[index]
}
},
})
Copy the code
11. Conditional rendering
1.v-if
- (1).v-if=”表达式”
- (2).v-else-if=”
- (3).v-else=” expression”
- Applicable to: Scenarios with low switching frequency.
- Features: DOM elements that are not shown are removed.
- Note: v-if can be used with :v-else-if and v-else, but the structure must not be “broken”.
2.v-show
- V-show =” expression”
- Applicable to: Scenarios with high switching frequency.
- Features: DOM elements that are not displayed are not removed, just hidden with styles
- Note: With v-if, the element may not be retrieved. With v-show, the element must be retrieved.
12. List rendering
V – for instructions
- 1. Display list data
- V -for=”(item, index) in XXX “:key=”yyy”
- 3. Traversable: arrays, objects, strings (rarely used), specified times (rarely used)
<! --> < span style = "max-width: 100%; clear: both;<h2>List of people (Traversal number group)</h2>
<ul>
<li v-for="(p,index) of persons" :key="index">
{{p.name}}-{{p.age}}
</li>
</ul><! -- Traverse the object --><h2>Car information (traversal object)</h2>
<ul>
<li v-for="(value,k) of car" :key="k">
{{k}}-{{value}}
</li>
</ul><! -- Iterate over the string --><h2>Test traversal of strings (used sparingly)</h2>
<ul>
<li v-for="(char,index) of str" :key="index">
{{char}}-{{index}}
</li>
</ul><! -- traversal the specified number of times --><h2>Test traversal specified number of times (used less)</h2>
<ul>
<li v-for="(number,index) of 5" :key="index">
{{index}}-{{number}}
</li>
</ul>
Copy the code
The principle of the key
- React and Vue keys (Key’s internal principles)
-
- Key functions in the virtual DOM:
- Key is the identity of the virtual DOM object. When the data changes, Vue will generate a new virtual DOM based on the new data.
- Then Vue compares the difference between [new virtual DOM] and [old virtual DOM], and the comparison rules are as follows:
-
2. Comparison Rules:
- (1). The same key as the new virtual DOM is found in the old virtual DOM:
- If the content in the virtual DOM has not changed, use the real DOM directly.
- (2) If the content in the virtual DOM changes, a new real DOM is generated and the previous real-DOM is replaced in the page.
-
(2). The same key as the new virtual DOM is not found in the old virtual DOM
-
Create a new real DOM and then render it to the page.
-
- Possible problems with index as key:
-
- If the data is added or deleted in reverse order, the sequence is broken:
- Produces unnecessary real DOM updates to the ==> interface, which is fine, but inefficient.
-
- If the structure also contains the DOM of the input class:
-
- Error DOM update ==> interface problem.
-
- How to select key in development? :
- 1. It is best to use the unique identifier of each piece of data as the key, such as ID, timestamp, random string, unique value.
- 2. It is only used for rendering the list for display if there is no operation of breaking the order such as adding or deleting the data in reverse order.
- 3. There is no problem with using index as the key (if there is a duplicate, the whole list will be recontaminated, if the ID is unique, only the new ID will be matched).
-
Vue monitoring data principle:
-
- Vue monitors all levels of data in data.
-
- How do I monitor data in objects?
- Monitoring is implemented through setters and the data to be monitored is passed in at new Vue.
- (1). Vue does not respond to the attributes appended to the object by default
- (2). If you need to respond to the attributes added later, please use the following API:
- Vue. Set (target, propertyName/index, value) or vm. set(target, propertyName/index, value)
-
- How do I monitor the data in an array?
- By wrapping the array update element, we essentially do two things:
- (1). Call the corresponding native method to update the array.
- (2). Reparse the template to update the page.
-
4. Use the following method to modify an element in Vue array:
- 1. Use these apis: Push (), pop(), Shift (), unshift(), splice(), sort- (), reverse()
- 2. Vue. The set () or vm. $set ()
-
Special note: vue.set () and vm.$set() cannot add attributes to the VM or the root data object of the VM!!
13. Collect form data
-
If:, then v-Model collects value and user input is value.
-
If:, the V-model collects value values and needs to configure value values for labels.
-
If:
-
1. If the value attribute for input is not configured, checked is checked.
-
2. Configure the input value property:
- (1) The initial value of v-model is not an array, then checked is collected (checked or is not checked, – is a Boolean value)
- (2) The initial value of v-Model is an array, so the collection is an array of values
-
Note: Three modifiers for v-model:
- Lazy: Data is collected after losing focus
- Number: Converts the input string into a valid number
- Trim: Enter the first and last Spaces
14. Filters
<h3>{{time | timeFormater}}</h3>
<h3>{{time | timeFormater(params)| mySlice}}</h3>Global filter vue.filter ('mySlice'.function(value){
return value.slice(0.4)}) local filtersfilters: {timeFormater(value,str='YYYy-mm-DD' HH: MM :ss'){
return dayjs(value).format(str)
}
}
Copy the code
15. Built-in instructions
V – text instructions:
- 1. Function: Render text content to its node.
- 2. The difference with interpolation syntax: V-text replaces the contents of the node, {{xx}} does not.
Hello, {{name}}</div><div v-text="name"></div>
Copy the code
V – HTML commands:
- 1. Function: Render content containing HTML structure to a specified node.
- 2. Differences with interpolation syntax:
- (1). V-html will replace all content in the node, {{xx}} will not.
- (2). V-html can recognize HTML structure.
- 3. Serious note: V-HTML has security problems !!!!
- (1). Dynamic rendering of arbitrary HTML on a website is very dangerous and can easily lead to XSS attacks.
- (2). Always use V-HTML for trusted content, never user-submitted content!
<div v-html="str"></div>
data:{
str:' Hello!
'
}
Copy the code
V-cloak instruction (no value) :
- 1. The v-cloak property is a special property that will be deleted when the Vue instance is created and takes over the container.
- 2. Use CSS and V-cloak to solve the problem that {{XXX}} is displayed when the network speed is slow.
V – once:
- 1. The node where v-once resides is regarded as static content after the initial dynamic rendering.
- 2. Future data changes will not cause the structure of V-once to be updated, which can be used to optimize performance.
V – pre:
- 1. Skip the compilation process of the node where the node resides.
- 2. Can use it to skip: no instruction syntax, no interpolation syntax of the node, will speed up the compilation.
16. Custom instructions
-
1. Define the syntax:
- New Vue({directives:{directives: object | | function}})
-
Configure the three common callbacks in the object:
- (1).bind: called when the instruction is successfully bound to an element.
- (2).inserted: Called when the element of the directive is inserted into the page.
- (3). Update: called when the template structure where the instruction resides is re-parsed.
-
Iii. Remarks:
- 1. Instructions are not defined with v-, but used with V -;
- 2. If the command name is multiple words, use kebab-case instead of camelCase.
< h2 > zoom in10<span v-big="n"></span> </h2>
<input type="text" v-fbind:value="n">Data :{name:'test', n:1}, caching :{// When will the BIG function be called? 2. When the template in which the directive resides is reparsed. /* 'big-number'(element,binding){ // console.log('big') element.innerText = binding.value * 10 }, */ // function big(element,binding){console.log('big',this) // note that this is window // console.log('big') element.innertext = Value * 10}, // fbind:{bind(element,binding){element.value = binding. Inserted (Element,binding){element.focus()}, Update (element,binding){element.value = binding. Value}}}Copy the code
17. Life cycle
-
1. Also known as: lifecycle callback, lifecycle function, lifecycle hook.
-
2. What it is: Some specially named functions Vue calls for us in the Nick of time.
-
3. The name of the lifecycle function cannot be changed, but the details of the function are written by the programmer according to the requirements.
-
4. The this in the lifecycle function refers to the VM or component instance object.
-
BeforeCreate (mount time)
-
Created (mount time)
-
BeforeMount (when mounting)
-
Mounted (mounted)
-
BeforeUpdate (when updating)
-
Updated
-
BeforeDestroy (when destroyed)
-
Destroyed (when destroyed)
Common lifecycle hooks:
- 1. Mounted (or created): Sends Ajax requests, starts a timer, bindings custom events, and subscribes messages.
- BeforeDestroy: Clear timers, unbind custom events, unsubscribe messages, etc.
About destroying Vue instances
- 1. No information can be seen with Vue developer tools after destruction.
- 2. Custom events are invalidated after destruction, but native DOM events are still valid.
- 3. Data is not normally manipulated beforeDestroy because even if it is manipulated, the update process is no longer triggered.
18. Non-single file components
-
Three steps to using components in Vue:
- Define component (create component)
- 2. Register components
- Three, use component (write component label – underlined name | | big hump name)
-
How to define a component?
- Create with vue.extend (options), where options and new Vue(options) passed the same options, but there are a few differences; The differences are as follows:
- 1. Don’t write el. Why? Ultimately, all components are managed by a VM, and the EL in the VM decides which container to serve.
- 2. Data must be written as a function. Why? ———— Prevents data from being referenced when components are reused.
- Note: You can configure the component structure using template.
- Create with vue.extend (options), where options and new Vue(options) passed the same options, but there are a few differences; The differences are as follows:
-
How to register a component?
- 1. Partial registration: Pass in the Components option when relying on new Vue
- 2. Global registration: by Vue.component(‘ component name ‘, component)
-
Iii. Write component labels:
-
A shorthand:
- Const school = vue. extend(options)
2. The scaffold
File structure
├ ─ ─ node_modules ├ ─ ─ public │ ├ ─ ─ the favicon. Ico: TAB icon │ └ ─ ─ index. HTML: main page ├ ─ ─ the SRC: directory entry │ ├ ─ ─ assets: For static resources │ │ └ ─ ─ logo. The PNG │ │ ─ ─ component: storage component │ │ └ ─ ─ the HelloWorld. Vue │ │ ─ ─ App. Vue: collect all components │ │ ─ ─ main. Js: ├─.gitignore: Git Version Control Ignored Config ├─ Babel.config. js: Babel Config File ├─ Package. json: Application Package Config File ├─ readme.md: git Version Control Ignored Config ├─ Babel.config. js: Babel Config File ├─ Package. json: Application Package Config File ├─ Application Description file ├─ package-lock.json: Package version control file
Vue. Config. js configuration file
- Use vue inspect > output.js to see the default configuration of vue scaffolding.
- Scaffolding can be customized using vue.config.js at cli.vuejs.org/zh
The plug-in
-
Features: Used to enhance Vue
-
Essence: An object that contains the install method. The first argument to Install is Vue and the second subsequent argument is data passed by the plug-in consumer.
-
Defining plug-ins:
Object. The install =function (Vue, options) {
// 1. Add a global filter
Vue.filter(....)
// 2. Add a global directive
Vue.directive(....)
// 3. Configure global mixin (combined)
Vue.mixin(....)
// 4. Add instance methods
Vue.prototype.$myMethod = function () {... } Vue.prototype.$myProperty = xxxx }Copy the code
- Using plug-ins:
Vue.use()
The ref attribute
- Is used to register reference information (a substitute for id) for an element or child component
- When applied to HTML tags, you get real DOM elements. When applied to component tags, you get component instance objects (VC).
- Usage:
- Play logo:
<h1 ref="xxx">..... </h1>
或<School ref="xxx"></School>
- Access to:
this.$refs.xxx
- Play logo:
Props configuration
-
Function: Enables a component to receive external data
-
-
Received data:
-
First method (accept only) : props:[‘name’]
-
Props :{name:String}
-
Third way (restrict type, restrict necessity, specify default) :
props: {name: {type:String./ / type
required:true./ / required
default:'Lao wang' / / the default value}}Copy the code
- Note: The props is read-only, and Vue will monitor any changes you make to the props and issue a warning if any changes are made. If the business requirements do need to be modified, copy the content of the props into a copy of the data and modify the data.
webStorage
-
The storage size is generally around 5MB (depending on the browser).
-
The browser implements the localStorage mechanism through the window. sessionStorage and window. localStorage properties.
-
The API:
-
xxxxxStorage.setItem('key', 'value');
- This method takes a key and value as arguments, adds the key-value pair to the store, and updates the corresponding value if the key name exists.Copy the code
xxxxxStorage.getItem('person');
– This method takes a key name as an argument and returns the value of the key name.
xxxxxStorage.removeItem('key');
– This method takes a key name as an argument and removes the key name from storage.
xxxxxStorage.clear()
– This method clears all data in the storage.
- Remark:
- The contents of SessionStorage will disappear when the browser window closes.
- The content stored in LocalStorage must be manually cleared before it disappears.
xxxxxStorage.getItem(xxx)
If the value corresponding to XXX cannot be obtained, the return value of getItem is null.JSON.parse(null)
Is still null.
Component custom events & component pass values
Props (Parent/child component transfer)
-
Parent component binding < chile-test@chileEventName =”fn”>
-
This.$emit(‘chileEventName’,params)
-
The parent component binds the event (rarely used) this.$refs.student.$on(‘chileEventName’,this.fn) // binds the custom event
-
This.$off(‘chileEventName’)
-
$refs.student.$once(‘EventName’,this.fn) // Bind the custom event to only one event
-
Native DOM events can also be bound to components, requiring the use of native modifiers.
Provide & Inject (Value transfer across level components)
- Progenitor components through dojo.provide: {objname: ‘value’ | | this} | | can also be the face directly to the components of this in the past
- Descendant components are received by inject[‘ objName ‘]
- $parent can also be used (not recommended)
slot
- The default slot | | named slot
- Difference: Named slots need to be named – multiple can be used
Category <div> <! Define a slot (dig a hole and wait for the user of the component to fill it)<slot>I am the default values that appear when the user does not pass in the concrete structure</slot>
</div>
App
<Category></Category> // If the component has no content, the slot content is displayed/ named slot
I'm some default value,
slot>
<Category>
<div slot="center"></div>
</Category>
Copy the code
- Scope slot
Category
<slot :data="slotList"</slot> I am some default value that will appear when the user does not pass in a structuredata() {
return {
slotList: [Code red.'Crossing the Line'.Dance Dance Company.Super Mario Bros.],
}
},
App
<Category >
<template scope="data">
<ul>
<li v-for="(g,index) in slotObj.slotList" :key="index">{{g}}</li>
</ul>
</template>
</Category>
Copy the code
Vue scaffold configuration agent
Methods a
- Add the following configuration to vue.config.js:
devServer: {proxy:"http://localhost:5000"
}
Copy the code
Description:
- Advantages: The configuration is simple. When requesting resources, you can send them directly to the front-end server (8080).
- Disadvantages: Multiple proxies cannot be configured, and you cannot flexibly control whether requests go through proxies.
- How it works: If the proxy is configured as above, when a request is made for a resource that does not exist in the front end, the request is forwarded to the server (matching the front end resource is preferred)
Method 2
- Write vue.config.js to configure specific proxy rules:
module.exports = {
devServer: {
proxy: {
'/api1': {// Matches all request paths starting with '/api1'
target: 'http://localhost:5000'.// The base path of the proxy target
changeOrigin: true.pathRewrite: {'^/api1': ' '} // Replace the starting path of the configuration with empty
},
'/api2': {// Matches all request paths starting with '/api2'
target: 'http://localhost:5001'.// The base path of the proxy target
changeOrigin: true.pathRewrite: {'^/api2': ' '}
}
}
}
}
Copy the code
- Advantages: You can configure multiple proxies and flexibly control whether requests go through proxies.
- Disadvantages: The configuration is cumbersome, and the prefix must be added when requesting resources.
Vuex (Centralized State Management)
-
Concept: a Vue plug-in that implements centralized state (data) management in Vue, centralized management (read/write) of the shared state of multiple components in Vue applications, is also a way of communication between components, and can be used for communication between any components.
-
Flow 1 (sync) Components (commit)->Mutations(commit)-> Change the data to the view
-
Flow 2 (asynchronous) Components (Dishpatch – distributed)-> Actinos ->Mutations(trigger,commit)-> change data to view
A
-----
<button @click="increment">Component A click</button>
<div>{{count}}</div>
<div>{{except}}}</div>
<button @click="incrementAsync">Asynchronous methods</button>----- methods: {sync... mapMutations(['adds']), //. mapMutations({customfn:'increment'}), asynchronous... mapActions(['delayedSync']),
// Rename it
addTen() {
// Call the mutations function and pass the parameters
this.$store.commit('increment'.10)}/ / use mapMutations
addTen() {
// Call the mutations function and pass the parameters
this.$store.commit('customfn'.10)}incrementAsync(){
// Process asynchronous dispatch - asynchronous method accept - changes state in asynchronous COMMIT
// this.$store.dispatch('delayedSync',2)
this.delayedSync(2)}}computed: {... mapState(['count']), // Use vuex heavy data - shorthand. mapState({'newname':'count'}) / / renamed. mapState({newname:state= >state.obj.name}) // The nesting level is deep (return by function). mapGetters(['except'])
},
-----
store/store.js
-----
import Vue from 'vue'
import Vuex from 'vuex' / / 1. Introduce the vuex
Vue.use(Vuex) //2. Mount on the prototype
// Create a VueX object
export default new Vuex.Store({ // Export store
state,
})
------
store/_state.js
-----
export default{
count:3 // Initialize the data} ------ store/ _blocksizes.js (simultaneous) ------// fn(state(store metadata object),Payload(call method pass params))
increment(state,count){ state.count+=count; }, ------ ------ store/_action.js (asynchronous)delayedSync(context,count){
setTimeout(() = >{
console.log('the action - asynchronous',context,count);
context.commit('increment',count)
},2000)
}
------
store/_getter.js
------
// Equivalent to computed
except(state){
return state.count*10} -- -- -- -- -- -Copy the code
- Replace Mutation event types with constants
// mutation-types.js
export const SOME_MUTATION = 'SOME_MUTATION'
Copy the code
Route
- A route is a group of key-values. Multiple routes need to be managed by routers.
- Front-end routing: Key is a path and value is a component.
1. Use basic routes
-
To install vue-router, run the NPM I vue-router command
-
Vue. Use (VueRouter)
-
Writing router configuration items:
<! Router router router router router router router router<router-link active-class="active" to="/home">Home</router-link><! -- Specify where to render the component --><router-view></router-view>
// This file is specifically used to create the router for the entire application
import VueRouter from 'vue-router'
// Import components
import Home from '.. /components/Home'
// Application plug-in
Vue.use(VueRouter)
/ / create the vm
new Vue({
el:'#root'.render: h= > h(App),
router
})
// Route lazy loading
const Foo = () = > import('./Foo.vue')
// Create and expose a router
export default new VueRouter({
mode: 'history'.// h5 history api
mode: 'hash'.// with # (using anchor points)
routes:[
{
// path: '*' // will match all paths
path:'/home'.// Matches the specified path
// path: '/' // Jumps to the page by default
component:Home,
children: [// Multilevel routing is nested through children
{
path:'news'.component:News,
/ / alias
alias: '/newName'
/ / redirection
redirect: '/b'| | {name: 'foo'} | |to= > {
// The method receives the destination route as an argument
// Return redirects the string path/path object}},]}, {// Name the route
name:'foo'.path:'foo/:id/:title||? Id (optional) '.component:Foo,
// If this is true, all params parameters received by the route component are passed to the current component as props, which can be received by the route component. Only params parameters are supported
// props:true
// functions (supports query)
props({query:{id,titke}}){
return {id,title}
}
}
]
})
Copy the code
2. A few caveats
- Routing components are typically stored
pages
Folders, where common components are usually storedcomponents
Folder. - By switching, routing components that are “hidden” are destroyed by default and mounted as needed.
- Each component has its own
$route
Property, which stores its own routing information. - The entire application has only one router that can pass through the component
$router
Property is obtained.
3. Query parameters of the route
-
Passing parameters
<! <router-link :to="/home/message/detail? Id =666&title= hello "> </router-link> <! -- jumps and takes the query argument, <router-link :to="{path:'/home/message/detail', query:{id:666, title:' hello '}}" > jump </router-link>Copy the code
-
Receiving parameters:
- This $route. Query. Id | | or by routing configuration function mode of props
4. Programmatic routing navigation
- Purpose: Without help
<router-link>
Realize the route jump, give way by jump more flexible
//$router two apis
this.$router.push({
name:'xiangqing'.params: {id:xxx,
}
})
this.$router.replace({
name:'xiangqing'.params: {id:xxx
}
})
this.$router.forward() / / to go forward
this.$router.back() / / back
this.$router.go() // Can go forward or backward
Copy the code
5. Cache routing components
- Effect: Keeps undisplayed routing components mounted and not destroyed.
- Two new lifecycle hooks (
Two hooks unique to a routing component that capture the active state of the routing component
) activated
Triggered when the routing component is activated.deactivated
Triggered when the routing component is inactivated.
<keep-alive include="News">
<router-view></router-view>
</keep-alive>
Copy the code
6. Route guard
-
Role: Controls the permission of routes
-
Categories: Global guard, exclusive guard, component inside guard
-
Global guard:
// Global front-guard: executed at initialization and before each route switch
router.beforeEach((to,from,next) = >{
console.log('beforeEach',to,from)
if(to.meta.isAuth){ // Determine whether permission control is required for the current route
if(localStorage.getItem('school') = = ='zxy') {// Specific rules for permission control
next() / / release
}else{
alert('No permission to view')
// next({name:'guanyu'})}}else{
next() / / release}})// Global post-guard: executed at initialization and after each route switch
router.afterEach((to,from) = >{
console.log('afterEach',to,from)
if(to.meta.title){
document.title = to.meta.title // Change the title of the page
}else{
document.title = 'vue_test'}})Copy the code
- Exclusive guard:
beforeEnter(to,from,next){
console.log('beforeEnter',to,from)
if(to.meta.isAuth){ // Determine whether permission control is required for the current route
if(localStorage.getItem('school') = = ='atguigu'){
next()
}else{
alert('No permission to view')
// next({name:'guanyu'})}}else{
next()
}
}
Copy the code
- Component internal guard:
// Enter guard: is called when entering this component by routing rules
beforeRouteEnter (to, from, next) {
},
// Leave guard: is called when leaving the component by routing rules
beforeRouteLeave (to, from, next) {
}
` `'### 13. Two working modes of router #### Two working modes of router 1. What is a hash value for a URL? The hash value is # and everything after it. 2. The hash value is not included in the HTTP request, that is, the hash value is not sent to the server. 3. Hash mode: 1. Addresses always contain hash signs, which is ugly. 2. If the IP address is shared through a third-party mobile app, the IP address will be marked as invalid if the APP verification is strict. 3. Good compatibility. 4. History mode: 1. The address is clean and beautiful. 2. Compatibility is slightly worse than hash mode. 3. When the application is deployed and goes online, the support of back-end personnel is required to solve the problem of refreshing server 404 on the page.Copy the code