Quick Start#
Environment Configuration#
Get the vue.js file
Go to the official website to download vue2
Remove Browser Prompts#
- Download Developer Tools for the Browser
2. Disable Production Tips in HTML JS Script
<script>
Vue.config.productionTip = false // Disable production vue tips
</script>
Basic Usage#
Create Container#
Other Ways to Write el#
<script>
Vue.config.productionTip = false // Disable production vue tips
const v = new Vue({
// el:"#app",
data: {
name: "miaolme"
}
})
// Execute after 1s
setTimeout(() => {
v.$mount("#app") // Set el
}, 1000);
</script>
Two Ways to Write data#
Function Style
// 1. Create core vue object
new Vue({
el:"#app",
data: function(){
return {
username:""
}
}
});
Short Style
// 1. Create core vue object
new Vue({
el: "#app",
data() {
return {
username: ""
}
}
})
Example
<!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>Vue Usage</title>
<script src="./js/vue2.js"></script>
</head>
<body>
<div id="app">
<input v-model="username">
<!-- Interpolation Expression -->
{{username}}
</div>
</body>
<script>
// 1. Create core vue object
new Vue({
el: "#app",
data() {
return {
username: ""
}
}
})
</script>
</html>
Common Vue Directives#
Directive: Special attributes with a V- prefix on HTML tags, different directives have different meanings
Directive | Function |
---|---|
v-bind | Bind attribute values to HTML tags, such as setting href , css styles, etc. |
v-model | Create two-way data binding on form elements |
v-on | Bind events to HTML tags |
v-if v-else v-else-if | Conditionally render an element, render if true, otherwise do not render |
v-show | Show an element based on a condition, the difference is that the display property value is toggled |
v-for | List rendering, iterate over elements of a container or properties of an object |
v-model#
v-model creates two-way data binding on form elements
Changes in the form will affect the entire vue setting value
v-bind#
Modify href
, css
styles, etc.
<!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>Vue Usage</title>
<script src="./js/vue2.js"></script>
</head>
<body>
<div id="app">
<a v-bind:href="url">Click Here</a>
<br>
<a :href="url">Shortened Format</a>
</div>
</body>
<script>
// 1. Create core vue object
new Vue({
el: "#app",
data() {
return {
username: "",
url: "https://baidu.com"
}
}
})
</script>
</html>
v-on#
Define Events
<!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>Vue Usage</title>
<script src="./js/vue2.js"></script>
</head>
<body>
<!-- The id in this div determines whether vue is available below -->
<div id="app">
<input type="button" value="A Button" v-on:click="show()">
<br>
<!-- Shortened Writing -->
<input type="button" value="Second Button" @click="show()">
</div>
</body>
<script>
// 1. Create core vue object
new Vue({
el: "#app",
data() {
return {
username: "",
url: "https://baidu.com"
}
},
methods: {
show() {
alert("I was clicked", number)
}
}
/*
methods: {
show(number) { // Can pass parameters
alert("I was clicked", number)
}
}
*/
})
</script>
</html>
<input type="button" value="A Button" v-on:click="show()">
<!-- Shortened Writing -->
<input type="button" value="Second Button" @click="show()">
v-for#
List rendering, iterate over elements of a container or properties of an object
v-for:
<div v-for='addr in addrs'>
{{addr}}<br>
</div>
Add Index
<div v-for="(addr,i) in addrs">
<!-- i represents the index, starting from 0 -->
{{i + 1}}:{{addr}}<br>
</div>
<!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="./js/vue2.js"></script>
</head>
<body>
<div id="app">
<div v-for="addr in addrs">
{{addr}} <br>
</div>
<hr>
<div v-for="(addr,i) in addrs">
{{i+1}}--{{addr}} <br>
</div>
</div>
</body>
<script>
new Vue({
el: "#app",
data() {
return {
addrs: ["Beijing", "Shanghai", "Tianjin"]
}
}
})
</script>
</html>
Vue Data Proxy#
Adding Data to Objects#
Object.defineProperty
<script>
let person = {
name: "Zhang San",
sex: "Male"
}
Object.defineProperty(person, 'age', {
value: 18 // Add a new key-value pair age:18 to the person object
enumerable: true // Control whether the property is enumerable, default false
writable: true // Control whether the property can be modified, default false
configurable: true // Control whether the property can be deleted, default false
})
console.log(person) //{name: 'Zhang San', sex: 'Male', age: 18}
</script>
Default: Non-enumerable, non-iterable, non-modifiable, non-deletable
let person = {
name: "Zhang San",
sex: "Male"
}
let number = 18
Object.defineProperty(person, 'age', {
/*
get: function () {
return number // Each time calling age will return number
}
*/
// Shortened
get(){
return number // Each time calling age will return number
},
// When someone modifies the age property of person, the set function (setter) will be called, and it will receive the specific value of the modification
set(value){
console.log('Someone modified the age property, and the modified value is', value)
number = value
}
})
console.log(person)
Event Handling#
new Vue({
el: "#App",
data: {
name: 'xingli'
},
methods: {
showInfo(e) {
console.log(e.target.value)
}
},
})
Methods written in the method section
v-on#
Used for event binding, can use @ instead, for example @click
@click.stop Stop event bubbling
Event Modifiers in Vue:
1.prevent: Prevent default events (commonly used);
2.stop: Prevent event bubbling (commonly used);
3.once: Event triggers only once (commonly used);
4.capture: Use the event capture mode; Event handling occurs during the event capture phase, from top to bottom
5.self: The event only triggers if event.target is the currently operated element;
6.passive: The default behavior of the event executes immediately without waiting for the event callback to finish;
Keyboard Events#
Bind vue key events with @
Commonly used @keydown
@keyup
Common key aliases in Vue:
- Enter => enter
- Delete => delete (captures both “Delete” and “Backspace” keys)
- Escape => esc
- Space => space
- Tab => tab
- Up => up
- Down => down
- Left => left
- Right => right
<!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="./js/vue2.js"></script>
</head>
<body>
<div id="App">
<input type="text" placeholder="Press Enter to prompt input" @keyup="showInfo">
</div>
</body>
<script>
new Vue({
el: "#App",
data: {
name: 'xingli'
},
methods: {
showInfo(e) {
if (e.keyCode !== 13) return // Set to return input value when Enter is pressed
console.log(e.target.value)
}
},
})
</script>
</html>
- For keys that Vue does not provide aliases, you can use the original key value to bind, but be careful to convert to kebab-case (hyphen naming)
showInfo(e) {// Using this code can get the key value
console.log(e.key)
console.log(e.keyCode)
}
4. You can also use keyCode to specify specific keys (not recommended) Different keyboards have different keyCodes
5. Vue.config.keyCodes. Custom key name = key code can customize key aliases
3. System Modifier Keys (special usage): ctrl, alt, shift, meta
(1). Used with keyup: The event is triggered only when the modifier key is pressed simultaneously with another key, and then the other key is released.
(2). Used with keydown: The event is triggered normally.
Modifiers can be written continuously with .#
@keyup.ctrl.y
Trigger the event when pressing ctrl+y
@click.prevent.stop
First prevent the default event, then stop bubbling
Computed Properties and Watchers#
Computed Properties computed#
<!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="./js/vue2.js"></script>
</head>
<body>
<div id="App">
Last Name<input type="text" v-model="firstName"> <br> <br>
First Name<input type="text" v-model="lastName"> <br> <br>
Full Name: <span>{{fullName}}</span>
</div>
</body>
<script>
new Vue({
el: '#App',
data: {
firstName: 'Zhang',
lastName: 'San'
},
computed: {
fullName: {// Finally exists in data
get() {
console.log('get was called')
return this.firstName + '-' + this.lastName
},
/* set(value) {
console.log('set was called', value)
const arr = value.split('-') // There is a - between the array
this.firstName = arr[0]
this.lastName = arr[1]
} */
}
},
})
</script>
</html>
Computed property shorthand
computed: {
fullname:function(){// Only consider reading, not modifying
console.log('get was called')
return this.firstName + '-' + this.lastName
}
}
Watch Properties watch#
<!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="./js/vue2.js"></script>
</head>
<body>
<div id="app">
<!-- <h2>Today's weather is very {{ishot ? 'hot' : 'cool'}}</h2> -->
<h2>Today's weather is very {{info}}</h2>
<br>
<button @click="gaiTian">Switch Weather</button> <br>
Tip: <h3>{{tip}}</h3>
</div>
</body>
<script>
const vm = new Vue({
el: '#app',
data: {
ishot: true,
tip: 'Drink more cold water',
},
computed: {
info() {
return this.ishot ? 'hot' : 'cool'
}
},
watch: {
ishot: {
immediate: true,// Boolean value whether to execute the function during initialization
handler() { // Only handler function can be used here
console.log('ishot was modified')
}
}
},
methods: {
gaiTian() {
if (this.ishot)
this.ishot = false; else this.ishot = true
}
},
})
// Another way to watch
/* vm.$watch('ishot', {//, write the monitored object in front, and write the function and configuration behind, the monitored object will not report an error when it does not exist
immediate: true,// Boolean value whether to execute the function during initialization
handler() { // Only handler function can be used here
console.log('ishot was modified')
}
}) */
</script>
</html>
Deep Watch#
Vue can detect changes in the internal values of objects, but the watch provided by Vue does not allow deep watching by default
Decide whether to enable deep watching based on actual conditions
<!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="./js/vue2.js"></script>
</head>
<body>
<div id="app">
<!-- <h2>Today's weather is very {{ishot ? 'hot' : 'cool'}}</h2> -->
<h2>Today's weather is very {{info}}</h2>
<br>
<button @click="gaiTian">Switch Weather</button> <br>
<button @click="numbers.a++">Click me to make a +1</button>
<h3>The value of a is {{numbers.a}}</h3> <br>
<br>
<button @click="numbers.b++">Click me to make b +1</button> <br>
<h3>The value of b is {{numbers.b}}</h3>
</div>
</body>
<script>
const vm = new Vue({
el: '#app',
data: {
ishot: true,
numbers: {
a: 1,
b: 2
}
},
computed: {
info() {
return this.ishot ? 'hot' : 'cool'
}
},
watch: {
ishot: {
handler() { // Only handler function can be used here
console.log('ishot was modified')
}
},
/* // Monitor changes in a certain property in a multi-level structure
'numbers.a': {// This writing is the original writing
handler() {
console.log('a changed')
}
} */
// Monitor changes in all properties in a multi-level structure, if not opened, the function will only take effect when all values in numbers change
numbers: {
deep: true,
handler() {
console.log('The value of numbers changed')
}
}
},
methods: {
gaiTian() {
if (this.ishot)
this.ishot = false; else this.ishot = true
}
},
})
</script>
</html>
Watch Shorthand#
watch: {
/*ishot: { // Normal writing
handler(newValue, oldValue) { // Only handler function can be used here
console.log('ishot was modified', newValue, oldValue)
}
}, */
ishot(newValue, oldValue) {
console.log('ishot was modified', newValue, oldValue)
},
},
Style Binding#
Binding Class Styles#
<div id="app">
<div class ="basic" :class="a">
<!-- The class of the above div is "basic normal" -->
</div>
<!-- Add multiple styles -->
<div class ="basic" :class="addr">
<!-- The class of the above div is "basic class1 class2 class3" -->
</div>
</div>
<script>
new Vue({
el:'#app',
data:{
a:'normal',
addr:['class1','class2','class3']
},
methods: {
change:{
}
},
})
</script>
Math.floor(Math.random()*3) // Random number range 0-3
// floor rounds down
// Math.random() generates a number from 0 to 1, not including 1, *3 means generating a number from 0 to 3, not including 3, generating a decimal
Binding Style Styles#
<body>
<div id="app">
<div class="" :style="{fontSize: fsize + 'px'}">{{name}}</div>
<!-- :style indicates that the content after the equal sign is an expression, the above code can change the font size -->
</div>
</body>
<script>
new Vue({
el: '#app',
data: {
a: 'normal',
name: 'miaolme',
fsize: 40
},
})
</script>
Another way to write
<body>
<div id="app">
<div class="" :style="styleObj">{{name}}</div>
<!-- :style indicates that the content after the equal sign is an expression, the above code can change the font size -->
</div>
</body>
<script>
new Vue({
el: '#app',
data: {
a: 'normal',
name: 'miaolme',
styleObj:{
fontSize:'40px',
backgroundColor: 'orange',
color: 'red'
}
},
})
</script>
Array Writing
<body>
<div id="app">
<div class="" :style="[styleObj,styleObj2]">{{name}}</div>
<!-- :style indicates that the content after the equal sign is an expression, the above code can change the font size -->
</div>
</body>
<script>
new Vue({
el: '#app',
data: {
a: 'normal',
name: 'miaolme',
styleObj: {
fontSize: '40px',
backgroundColor: 'orange',
color: 'red'
},
styleObj2: {
color: 'red'
}
},
})
</script>
Conditional Rendering#
v-show and v-if#
<body>
<div id="app">
<!-- v-show writes an expression after the equal sign, the result is a boolean value
v-if and v-show have the same usage -->
<!-- <h2 v-show="false">Welcome to learn vue{{name}}</h2> -->
<!-- <h2 v-show="1===1">Welcome to learn vue{{name}}</h2> -->
<h2 v-if="false">Welcome to learn vue{{name}}</h2>
</div>
</body>
<script>
new Vue({
el: '#app',
data: {
name: 'miaolme'
}
})
</script>
v-else-if and v-else#
Usage is the same as conventional programming's else if
After if executes
else if's code does not execute
If all conditions are not met, execute the code in else
v-show is suitable for scenarios with high switching frequency
v-if is suitable for scenarios with low switching frequency
Can be nested using div
List Rendering#
v-for#
<body>
<div id="app">
<h2>Personnel List</h2>
<ul>
<!-- Generate li based on the length of the persons array -->
<!-- key represents node identification -->
<li v-for="ren in persons" :key="ren.id">
<!-- in can be replaced with of -->
{{ren.name}}-{{ren.age}}
</li>
</ul>
</div>
</body>
<script>
new Vue({
el: '#app',
data: {
persons: [
{ id: '001', name: 'Zhang San', age: 18 },
{ id: '002', name: 'Li Si', age: 19 },
{ id: '003', name: 'Wang Wu', age: 20 }
]
}
})
</script>
<body>
<div id="app">
<h2>Personnel List</h2>
<ul>
<!-- Generate li based on the length of the persons array -->
<!-- key represents node identification -->
<!-- index can be replaced with other words, it is the index and can access this data -->
<li v-for="(ren,index) in persons" :key="ren.id">
<!-- in can be replaced with of -->
{{ren.name}}-{{ren.age}}-{{index}}
</li>
</ul>
</div>
</body>
v-for can iterate over other data
<body>
<div id="app">
<h2>Personnel List</h2>
<ul>
<!-- Generate li based on the length of the persons array -->
<!-- key represents node identification -->
<!-- index can be replaced with other words, it is the index and can access this data -->
<li v-for="(value,key) in neko" :key="key.id">
{{key}}-{{value}}
<!-- Similar to key-value pairs -->
</li>
</ul>
</div>
</body>
<script>
new Vue({
el: '#app',
data: {
neko: {
mao: 'Pink Fur',
eye: 'Big Eyes',
tile: 'Big Tail'
}
}
})
</script>
v-for can iterate over strings
<body>
<div id="app">
<h2>Personnel List</h2>
<ul>
<!-- Generate li based on the length of the persons array -->
<!-- key represents node identification -->
<!-- index can be replaced with other words, it is the index and can access this data -->
<li v-for="(char,index) in str" :key="index.id">
{{index}}-{{char}}
<!-- Similar to key-value pairs -->
</li>
</ul>
</div>
</body>
<script>
new Vue({
el: '#app',
data: {
str: 'Hello'
}
})
</script>
Rarely used
v-for can iterate a specified number of times
<body>
<div id="app">
<h2>Personnel List</h2>
<ul>
<!-- Generate li based on the length of the persons array -->
<!-- key represents node identification -->
<!-- index can be replaced with other words, it is the index and can access this data -->
<li v-for="(number,index) in 5" :key="index.id">
{{number}}-{{index}}
<!-- Similar to key-value pairs -->
</li>
</ul>
</div>
</body>
The value of key must be unique
List Features#
Filtering#
1 Two-way binding
2 Judgment + color change
.indexOf()
This method checks whether the number before the dot contains the character in ()
If it contains, it will give the position, the first position is 0
, if it does not contain, it returns -1
this.persons = this.persons.filter((p) => {
return p.name.indexOf(val) !== -1
})
// filter filtering method
Array.filter((variable) => {
return boolean value
})
// Returns a new array
Complete watch method
<body>
<div id="app">
<div>
<input type="text" placeholder="Please enter a name" v-model="keyWord">
<button>This is a button</button>
<ul>
<li v-for="(p, index) in fillPersons" :key="p.id">
{{p.name}}-{{p.age}}-{{p.sex}}
</li>
</ul>
</div>
</div>
</body>
<script>
new Vue({
el: '#app',
data: {
persons: [
{ id: '001', name: 'Ma Dongmei', age: 19, sex: 'Female' },
{ id: '002', name: 'Zhou Dongyu', age: 20, sex: 'Female' },
{ id: '003', name: 'Jay Chou', age: 21, sex: 'Male' },
{ id: '004', name: 'Wen Zhaolun', age: 22, sex: 'Male' }
],
keyWord: '',
fillPersons: []
},
watch: {
keyWord: {
immediate: true,
handler(val) {
this.fillPersons = this.persons.filter((p) => {
return p.name.indexOf(val) !== -1
})
}
}
}
})
</script>
</html>
Using computed to achieve
<body>
<div id="app">
<div>
<input type="text" placeholder="Please enter a name" v-model="keyWord">
<button>This is a button</button>
<ul>
<li v-for="(p, index) in fillPersons" :key="p.id">
{{p.name}}-{{p.age}}-{{p.sex}}
</li>
</ul>
</div>
</div>
</body>
<script>
new Vue({
el: '#app',
data: {
persons: [
{ id: '001', name: 'Ma Dongmei', age: 19, sex: 'Female' },
{ id: '002', name: 'Zhou Dongyu', age: 20, sex: 'Female' },
{ id: '003', name: 'Jay Chou', age: 21, sex: 'Male' },
{ id: '004', name: 'Wen Zhaolun', age: 22, sex: 'Male' }
],
keyWord: '',
},
computed: {
fillPersons() {
return this.fillPersons = this.persons.filter((p) => {
return p.name.indexOf(this.keyWord) !== -1
})
}
},
})
</script>
</html>
Sorting#
Vue Data Detection Principle#
Too lazy to learn
See here:
033_Shangguigu Vue Technology_An Issue During Update_Bilibili
See 037
Collecting Form Data#
v-model default two-way binding value value
<!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="./js/vue2.js"></script>
</head>
<body>
<div id="app">
<form @submit.prevent="demo">
<!-- Clicking the button triggers form submission, prevent prevents the default behavior -->
<!-- <label for="demo"> -->
<!-- label and id can connect two objects -->
<!-- Account: <input type="text" id="demo"> -->
<!-- </label> -->
Account: <input type="text" v-model="account"> <br>
Password: <input type="password" v-model="password"> <br>
Gender: <br>
Male<input type="radio" name="sex" value="male" v-model="sex">
<!-- The radio button can be grouped by name -->
Female<input type="radio" name="sex" value="female" v-model="sex">
<br>
Hobbies: <br>
<!-- vue defaults to read the checked boolean value of the checkbox -->
Study<input type="checkbox" v-model="hobby" value="study">
Play Games<input type="checkbox" v-model="hobby" value="game">
Eat<input type="checkbox" v-model="hobby" value="eat"> <br>
Campus <br>
<select v-model="city">
<option value="">Please select a campus</option>
<option value="beijing">Beijing</option>
<option value="shenzhen">Shenzhen</option>
<option value="shanghai">Shanghai</option>
<option value="wuhan">Wuhan</option>
<br>
</select> <br>
Other Information: <br>
<textarea v-model="other"></textarea> <br>
<input type="checkbox" v-model="agree"> Read and accept <a href="http://baidu.com">《User Agreement》</a> <br>
<button>Submit Information</button>
</form>
</div>
</body>
<script>
new Vue({
el: "#app",
data: {
account: '',
password: '',
sex: 'female',// Two-way binding will default select gender
hobby: [],// The value obtained by hobby from the checkbox is a string
city: '',
other: '',
agree: 'false',
},
methods: {
demo() {
alert(1)
}
},
})
</script>
</html>
Vue Basics#
Filters#
Effect: Display formatted time
Now is: 2021-01-09
Now is: 2021-01-09 22:53:47
Not very meaningful, removed in vue3
<script src="./js/vue2.js"></script>
<script src="./js/dayjs.min.js"></script>
</head>
<body>
<!-- Prepare a container -->
<div id="root">
<h2>Display formatted time</h2>
<h3>Now is {{fmtTime}}</h3>
</div>
</body>
<script>
new Vue({
el: '#root',
data: {
time: 1621561377603 // Timestamp
},
computed: {
fmtTime() {
return dayjs(this.time).format('YYYY-MM-DD HH:mm:ss')
}
}
})
</script>
</html>
Time formatting can be achieved with third-party libraries
Built-in Directives#
Learned Directives#
v-bind : One-way binding to parse expressions, can be shortened to: xxx
v-model : Two-way data binding
v-for : Iterate over arrays/objects/strings
v-on : Bind event listeners, can be shortened to @
v-if : Conditional rendering (dynamically control whether the node exists)
v-else : Conditional rendering (dynamically control whether the node exists)
v-show : Conditional rendering (dynamically control whether the node is displayed)
v-text Directive#
<body>
<div id="app">
<div>{{name}}</div> <br>
<div v-text="name"></div> <!-- v-text will replace the entire div content -->
<!-- v-text inserts text and will replace node content, interpolation syntax will not -->
</div>
</body>
<script>
new Vue({
el: '#app',
data: {
name: 'Kitten'
}
})
</script>
v-html Directive#
Usage: Same as v-text, but can parse strings with tags like <h2>Hehe</h2>
<div v-html="name"></div>
Security issues, used for input can ignore inserting dangerous html statements
v-cloak Directive#
Used in tags, the tag will disappear after vue is mounted
Can set styles separately, essentially an id that can set the content carrying that id not to display diskplay
, can prevent {{}}
content from appearing due to slow network speed before vue loads
v-once Directive#
- The node where v-once is located is considered static content after the initial dynamic rendering.
- Subsequent changes in data will not trigger updates to the structure where v-once is located, can be used for performance optimization.
The tag adds the content in {{}}
will only display the initial value
v-pre Directive#
- v-pre skips the compilation process of its node.
- It can be used to skip nodes that do not use directive syntax or interpolation syntax, speeding up compilation
Custom Directives#
Currently not needed
Lifecycle#
Principle Diagram
All fields below are at the same level as data:{}
in vue
new Vue({
el: '#app',
data: {
name: 'Kitten'
}
})
mounted#
mounted(){
// The code inside this function will only execute after vue is mounted
// You can add timer functions and other initialization code inside
}
template#
Usage 1: No line breaks
template:'<h2>The current value of n is: {{n}}/h2><button@click="add">Click me n+1</button>'
Usage 2: Line breaks
template:`<h2>The current value of n is: {{n}}/h2>
<button@click="add">Click me n+1</button>`
Function, replace the content of the container, i.e., all content inside <div id="app">
<div id="app">
<div>{{name}}</div> <br>
<div v-text="name"></div> <!-- v-text will replace the entire div content -->
<!-- v-text inserts text and will replace node content, interpolation syntax will not -->
</div>
Using template in vue will overwrite all content of the original container.
The template can be empty, but must contain template
(root node)
beforeUpdate#
Function before the update process
beforeUpdate(){
// The function written inside will execute before the vue value is about to update
}
update#
update(){
// The function written inside will execute after the vue value updates
}
beforeDestroy#
beforeDestroy(){
// The function written inside will execute before vue is about to destroy
// Mainly used to write termination functions for various services, such as ending timer functions, etc.
// Generally at this stage: close timers, unsubscribe messages, unbind custom events, and other finishing operations
}
Non-Single File Components#
Basic Example
<!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="./js/vue2.js"></script>
</head>
<body>
<!-- Define container -->
<div id="app">
<h1>{{msg}}</h1>
<hr>
<school />
</div>
</body>
<script>
// Define component
const school = Vue.extend({
template: `
<div>
<h2>My School: {{name}}</h2>
<h2>Address: {{address}}</h2>
</div>`,
data() {
return {
name: 'Meow School',
address: 'Meow Daughter Paradise'
}
}
})
new Vue({
el: '#app',
data: {
msg: 'Hello Vue!'
},
// Register component (local)
components: {
school: school // Use <school/> tag to use, the content of the tag is determined by the left side
}
})
</script>
</html>
Globally Register Component
// Globally register component
Vue.component('using tag name', defined component name)
Global Registration Example
Vue.component('xuexiao', school)
// Use <xuexiao/> to call this component
const school = Vue.extend({
template: `
<div>
<h2>My School: {{name}}</h2>
<h2>Address: {{address}}</h2>
</div>`,
data() {
return {
name: 'Meow School',
address: 'Meow Daughter Paradise'
}
}
})
Difference Between Local and Global Registration:
Locally registered components can only be used in their specified containers, globally registered components can be used in any container to call the component.
Components can be nested
But the execution order must be top-down, otherwise it will report an error
Constructor#
057_Shangguigu Vue Technology_VueComponent Constructor_Bilibili
Skip for now, learn later
Scaffold#
Install Scaffold#
- Install node.js
- Configure Taobao Source
npm config set registry=http://registry.npm.taobao.org
- Globally install scaffold
npm install -g @vue/cli
Create scaffold file
vue create file name # (self-defined) best not to appear in Chinese, may cause errors
Single File Components#
File suffix .vue
Naming Convention
school.vue my-school.vue
School.vue MySchool.vue
Structure
<template>
<!-- Structure of the component -->
</template>
<script>
// Code related to component interaction (data, methods, etc.)
</script>
<style>
/* Styles of the component */
</style>
Example
<template>
<div class="demo">
<h2>My School: {{name}}</h2>
<h2>Address: {{address}}</h2>
</div>
</template>
<script>
const school = Vue.extend({
data() {
return {
name: 'Meow School',
address: 'Meow Daughter Paradise'
}
}
})
</script>
<style>
.demo{
background-color: pink;
}
</style>
Expose Methods
Similar to public exposing methods, a total of 3 types
<script>
export const school = Vue.extend({ // respectively exposed
data() {
return {
name: 'Meow School',
address: 'Meow Daughter Paradise'
}
}
})
</script>
<script>
const school = Vue.extend({
data() {
return {
name: 'Meow School',
address: 'Meow Daughter Paradise'
}
}
})
export default school // Default export, commonly used
</script>
<script>
/* Or */
export default {
name:'school',
data() {
return {
name: 'Meow School',
address: 'Meow Daughter Paradise'
}
}
}
</script>
<script>
const school = Vue.extend({
data() {
return {
name: 'Meow School',
address: 'Meow Daughter Paradise'
}
}
})
export {school} // Unified export
</script>
App.vue Summary Component
<template lang="">
<div>
<school></school>
</div>
</template>
<script>
// Import component
import school from 'vue1/school'
export default {
name: 'App',
components: {
school: school
}
}
</script>
<style lang="">
</style>
vm main.js
import App from 'vue1/App'
new Vue({
template:'<App></App>',
el:'#root',
components:{App}
})
Entry File index.html
<!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>
</head>
<body>
<div id="root">
</div>
<script src="../js/vue2.js"></script>
<script src="./main.js"></script>
</body>
</html>
Common Properties#
Render Function#
main.js
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
new Vue({
render: h => h(App), // h can be replaced with other content, the following is an example
//render: test => test(App), similarly, App represents the component, can also be replaced with template structure
//render: test => test('h1','hello') similar to template effect, not commonly used
}).$mount('#app') // This is equivalent to el:'#app'
ref Element#
Function: Similar to id selector, used to get the vm object of the component or the object of a certain element
Example:
<h1 ref="sch">Hello Vue!</h1>
console.log(this.$refs.sch)
ref Attribute
Used to register reference information for elements or child components (replacement for id)
The element applied on the html tag gets the real dom element, the element applied on the component gets the component instance object (vc)
props Configuration#
Usage:
props:['name','address','age']
Used in script at the same level as data
Cannot have the same value as in data. Used for external data input.
You can control the values passed in through internal functions.
num+(){
this.age++ // Needs to use this
}
mixin Mixing#
Example
mixin.js
// Export separately
export const mixin = {
methods: {
showName() {
alert(this.name)
}
},
}
MyStudent.vue
<template>
<div>
<h3 @click="showName">Name: {{ name }}</h3>
<h3>Address: {{ address }}</h3>
<h3>Age: {{ age }}</h3>
</div>
</template>
<script>
// Import mixin
import { mixin } from '../mixin'
export default {
name: 'MyStudent',
data() {
return {
name: 'Meow Meow',
address: 'Sakura Campus',
age: '18'
}
},
// Enable mixin, will automatically call the custom method in the mixed-in based on structure
mixins: [mixin],
methods: {
}
}
</script>
The method in the component executes with priority
The mounted function will execute. The code in the mixin will execute first
Global Mixing
Just modify main.js
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
// Import mixin
import { mixin } from './mixin'
// Apply mixin
Vue.mixin(mixin)
new Vue({
render: h => h(App),
}).$mount('#app')
Scope Limitation and Plugins#
Scope Limitation
scoped#
Used in style
<style scoped>
.title{
color: red;
}
</style>
Function: Limits the styles in the style to only take effect in the current component.
Styles in vue will override the same name styles of the component
Plugins#
Usage Method: script.js
Define plugin
export default { // Default export
install(Vue,x,y){ // Can accept passed values x,y
// Global filter
Vue.filter('mySlice',function(value){...})
// Define global directive
Vue.directive('fbind',{...})
// Define global mixin
Vue.mixin({...})
}
// Add methods to vue prototype
Vue.prototype.hello = ()=>{alert('Hello vue')}
}
Apply plugin in App.vue
<script>
// Import plugin
import plugins from './plugins'
// Use plugin
Vue.use(plugins)
</script>
Component Information Interaction#
Global Event Bus#
Not learned 084_Shangguigu Vue Technology_Global Event Bus 1_Bilibili
Message Subscription and Publishing#
1 Subscribe to messages 2 Publish messages
Install Third-party Library
npm install [email protected]
Import school.vue
<script>
import pubsub from 'pubsub-js'
// Define
mounted(){ // If not written as an arrow function, the execution function needs to be defined in methods
this.pubId = pubsub.subscribe('hello',(msgName,data)=>{ // Subscribe to messages
console.log(this) // hello is the message name
})
}
// Unsubscribe
beforeDestroy(){
pubsub.unsubscribe(this.pubId)
}
</script>
Another Way
<script>
import pubsub from 'pubsub-js'
methods(){
demo(data){...}
}
mounted(){ // If not written as an arrow function, the execution function needs to be defined in methods
this.pubId = pubsub.subscribe('hello',this.demo) // Subscribe to messages
// When the hello event is published, the callback function will be executed
}
// Unsubscribe
beforeDestroy(){
pubsub.unsubscribe(this.pubId)
}
</script>
Publish Message
<script>
import pubsub from 'pubsub-js'
methods(){
sendStudentName(){
pubsub.publish('hello',666) // Calling this method will create a message named hello, data is 666
}
}
</script>
methods: $nextTick
this.$nextTick(function(){
// Will execute after the dom node is updated, vue template compilation is completed
this.$refs.inputTitle.focus()// Automatically get focus
})
setTimeout(){
this.$refs.inputTitle.focus()// Automatically get focus
// Timer function will execute after vue template compilation is completed
}
Transition and Animation#
Vue Animation#
<template>
<div>
<!-- isShow = !isShow means the button toggles isShow between true and false -->
<Button @click="isShow = !isShow">Show/Hide</Button>
<transition name="v" appear>
<!-- :appear="true" is equivalent to appear, adding it will play the animation after refresh -->
<!-- The transition tag automatically plays the animation of coming and going when set -->
<h1 v-show="isShow">Hello!</h1>
</transition>
</div>
</template>
<script>
export default {
name: 'MyTest',
data() {
return {
isShow: true
}
}
}
</script>
<style scoped>
h1 {
background-color: pink;
}
/* Add class to the required element to play the set animation */
.come {
/* Coming animation */
animation: dongHua 1s;
}
.go {
/* Leaving animation */
animation: dongHua 1s reverse;
/* reverse reverses */
}
/* Transition animation tag type v is the name of the animation */
.v-enter-active {
/* Coming animation */
animation: dongHua 1s;
}
.v-leave-active {
/* Leaving animation */
animation: dongHua 1s reverse;
/* reverse reverses */
}
@keyframes dongHua {
/* Define animation keyframes and animation name */
from {
transform: translateX(-100%);
/* Unit is px */
}
to {
transform: translateX(0px);
}
}
</style>
Vue Transition#
Example
<div>
<!-- isShow = !isShow means the button toggles isShow between true and false -->
<Button @click="isShow = !isShow">Show/Hide</Button>
<transition-group name="v">
<!-- :appear="true" is equivalent to appear, adding it will play the animation after refresh -->
<!-- The transition tag automatically plays the animation of coming and going when set -->
<h1 v-show="isShow" key="1">Hello!</h1>
<h1 v-show="isShow" key="2">Vue</h1>
</transition-group>
</div>
All elements in the group must have a unique key value
name is used to distinguish different types of animations
Integrating Third-party Animations#
animate.css - Third-party Animation (npmjs.com)
Installation:
Need to enter the required project in cmd to execute
npm install animate.css --save
Animate.css Development Documentation
Import
<script>
import 'animate.css';
</script>
Example
<template>
<div>
<!-- isShow = !isShow means the button toggles isShow between true and false -->
<Button @click="isShow = !isShow">Show/Hide</Button>
<transition-group
name="animate__animated animate__bounce"
appear
enter-active-class="animate__rubberBand"
leave-active-class="animate__bounceOut">
<!-- :appear="true" is equivalent to appear, adding it will play the animation after refresh -->
<!-- The transition tag automatically plays the animation of coming and going when set -->
<h1 v-show="isShow" key="1">Hello!</h1>
<h1 v-show="isShow" key="2">Vue</h1>
</transition-group>
</div>
</template>
<script>
// Import animation css
import 'animate.css'
export default {
name: 'MyTest2',
data() {
return {
isShow: true
}
}
}
</script>
<style scoped>
h1 {
background-color: pink;
}
</style>
enter-active-class=""
and leave-active-class=""
The content inside "" needs to fill in the name of the animation required by the animation library. name=""
must fill in animate__animated animate__bounce
Different animation libraries have slightly different requirements
All elements in the group must have a unique key value
Slots#
Default Slot#
Usage:
- Component writes double tags
- Fill in the elements that need to be added in the component inside the tags
- Use the slot double tags to mark the placement of the content in the component
The content written in the slot tag will be displayed when the content inside the component's double tags is empty
viedo wants to play must add controls tag to play
Named Slots#
Usage:
- Write
slot="defined name"
in the component double tags - Add
name="custom name"
attribute in theslot
tag
Using the same slot
name for different elements will not overwrite, it will automatically append
Another way to write
Using <template>
double tags to wrap, similar to div
but will not produce dom
structure
Using this tag to wrap can use v-slot:custom name
to define the position of the generated dom
Scoped Slots#
104_Shangguigu Vue Technology_Scoped Slots_Bilibili
Since it seems not very useful, I will not learn it for now
Vuex#
Understanding Vuex#
Principle Diagram
What is Vuex#
- Concept: A Vue plugin specifically designed to implement centralized state (data) management in Vue, centrally managing shared states in multiple components of the vue application (read/write), and is also a way of communication between components.
- GitHub Address: https://github.com/vuejs/vuexe
When to Use Vuex#
- Multiple components depend on the same state
- Actions from different components need to change the same state
Install Vuex#
npm i vuex@3
Dynamic Routing#
Basic Use of Routing#
- Need to install vue-router3
npm i vue-router@3
Plugin Library
Usage Method
main.js
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
// Disable Vue production tips
Vue.config.productionTip = false
// Apply plugin
Vue.use(VueRouter)
new Vue({
render: h => h(App),
}).$mount('#app')
Create Routing#
router/index.js
// This file is used to create the router for the entire application
import VueRouter from "vue-router";
// Import components
import MyHome from "../comments/home"
import MyAbout from "../comments/about"
// Create a router and export it
export default new VueRouter({
routes: [
{
path: '/about',
component: MyAbout
},
{
path: '/home',
component: MyHome
}
]
})
Import Router#
main.js
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
// Import router
import router from './router'
// Disable Vue production tips
Vue.config.productionTip = false
// Apply plugin
Vue.use(VueRouter)
new Vue({
render: h => h(App),
router: router // Import router
}).$mount('#app')
Adjust App.vue
<template>
<div>
<div class="row">
<div class="col-xs-offset-2 col-xs-8">
<div class="page-header">
<h2>Vue Router Demo</h2>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-2 col-xs-offset-2">
<div class="list-group">
<!-- In original html we use a tag to achieve page jump -->
<!-- <a class="list-group-item active" href="./about.html">About</a>
<a class="list-group-item" href="./home.html">Home</a> -->
<!-- Route jump router-link and to tag will eventually convert to a tag active-class is the style when the element is activated -->
<router-link class="list-group-item" active-class="active" to="/about">About</router-link>
<router-link class="list-group-item" active-class="active" to="/home">Home</router-link>
</div>
</div>
<div class="col-xs-6">
<div class="panel">
<div class="panel-body">
<!-- What component to display here depends on which navigation item the user clicks -->
<!-- Specify the position of the component to be presented -->
<router-view></router-view>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
}
},
components: {
}
}
</script>
<style>
</style>
It is recommended to put routing components in a separate folder
Nested (Multi-level) Routing#
router/index.js
// This file is used to create the router for the entire application
import VueRouter from "vue-router";
// Import components
import MyHome from "../comments/home"
import MyAbout from "../comments/about"
import MyNews from "../comments/news"
import MyMessage from "../comments/message"
// Create a router and export it
export default new VueRouter({
routes: [
{
path: '/about',
component: MyAbout
},
{
path: '/home',
component: MyHome,
// Secondary routing
children: [
{
path: 'news',
component: MyNews
},
{
path: 'message',
component: MyMessage
}
]
}
]
})
home.vue
<template>
<div>
<h2>Home Component Content</h2>
<div>
<ul class="nav nav-tabs">
<li>
<router-link class="list-group-item" active-class="active" to="/home/news">News</router-link>
</li>
<li>
<router-link class="list-group-item" active-class="active" to="/home/message">Message</router-link>
</li>
</ul>
<router-view></router-view>
</div>
</div>
</template>
<script>
export default {
name: 'MyHome'
}
</script>
<style>
</style>
Route Parameters#
Query Parameters#
You can pass parameters by writing ?…
after to
Jump route and carry query parameters, the string writing of to
<router-link class="list-group-item" active-class="active" to="/home/message?id=666&title=Hello!">Message</router-link>
Get parameters
{{$route.query.id}} //666
{{$route.query.title}} //Hello!
Using v-if
can insert specified content
<li v-for="m in messageList" :key="m.id">
<router-link class="list-group-item" active-class="active" :to="`/home/message?id=${m.id}&title=${m.title}`">Message</router-link>
</li>
Jump route and carry query parameters, the object writing of to
<li v-for="m in messageList" :key="m.id">
<router-link :to="{
path:'/home/message/detail',
query:{
id:m.id,
title:m.title
}
}"
</li>
Named Routes#
Add method router/index.js
// This file is used to create the router for the entire application
import VueRouter from "vue-router";
// Import components
import MyHome from "../comments/home"
import MyAbout from "../comments/about"
import MyNews from "../comments/news"
import MyMessage from "../comments/message"
// Create a router and export it
export default new VueRouter({
routes: [
{
name:'guanyu', // Give a name to whoever is named here
path: '/about',
component: MyAbout
},
{
path: '/home',
component: MyHome,
// Secondary routing
children: [
{
path: 'news',
component: MyNews
},
{
name:'xiangqing', // Give a name to whoever is named here
path: 'message',
component: MyMessage
}
]
}
]
})
Can simplify operations
Only supports the following two
<li v-for="m in messageList" :key="m.id">
<router-link :to="{
name:'xiangqing',
query:{
id:m.id,
title:m.title
}
}"
</li>
<router-link class="list-group-item" active-class="active" :to="{name:'guanyu'}">About</router-link>
Params Parameters#
Configure Routing
// This file is used to create the router for the entire application
import VueRouter from "vue-router";
// Import components
import MyHome from "../comments/home"
import MyAbout from "../comments/about"
import MyNews from "../comments/news"
import MyMessage from "../comments/message"
import MyDetail from "../comments/detail"
// Create a router and export it
export default new VueRouter({
routes: [
{
name:'guanyu', // Give a name to whoever is named here
path: '/about',
component: MyAbout
},
{
path: '/home',
component: MyHome,
// Secondary routing
children: [
{
path: 'news',
component: MyNews
},
{
name:'xiangqing', // Give a name to whoever is named here
path: 'message',
component: MyMessage,
children:{
{
name:'xiangqing',
path:'detail/:id/:title'
component: MyDetail,
}
}
}
]
}
]
})
Carrying Method 1
<li v-for="m in messageList" :key="m.id">
<router-link class="list-group-item" active-class="active" :to="`/home/message/detail/${m.id}/${m.title}`">Message</router-link>
</li>
Carrying Method 2
Cannot use path
<li v-for="m in messageList" :key="m.id">
<router-link :to="{
name:'xiangqing',
params:{
id:m.id,
title:m.title
}
}"
</li>
Route Props Configuration#
Matching Detail
Component
<template>
<ul>
<li>Message Number: {{ id }}</li>
<li>Message Title: {{ title }}</li>
</ul>
</template>
<script>
export default {
name: 'Detail',
props: ['id', 'title']
}
</script>
<style>
</style>
Second Way of Writing
// This file is used to create the router for the entire application
import VueRouter from "vue-router";
// Import components
import MyHome from "../comments/home"
import MyAbout from "../comments/about"
import MyNews from "../comments/news"
import MyMessage from "../comments/message"
// Create a router and export it
export default new VueRouter({
routes: [
{
path: '/about',
component: MyAbout
},
{
path: '/home',
component: MyHome,
// Secondary routing
children: [
{
path: 'news',
component: MyNews
},
{
path: 'message',
component: MyMessage,
// The second way of writing props, the value is a boolean, if the boolean value is true, it will pass all params parameters received by the route component
// as props to the Detail component
props:true
}
]
}
]
})
Another Way of Writing
// This file is used to create the router for the entire application
import VueRouter from "vue-router";
// Import components
import MyHome from "../comments/home"
import MyAbout from "../comments/about"
import MyNews from "../comments/news"
import MyMessage from "../comments/message"
// Create a router and export it
export default new VueRouter({
routes: [
{
path: '/about',
component: MyAbout
},
{
path: '/home',
component: MyHome,
// Secondary routing
children: [
{
path: 'news',
component: MyNews
},
{
path: 'message',
component: MyMessage,
// The third way of writing props, the value is a function
// 1.
/*props({ query: { id, title } }) {
return { id, title }
} */
// 2.
/* props({ query }) {
return { id: query.id, title: query.title }
} */
// 3.
props($route) {
return {
id: $route.query.id,
title: $route.query.title
}
}
}
]
}
]
})
Programmatic Route Navigation#
push View#
Button Passing Parameters
<button> @click="pushShow(m)" push view</button>
Button Binding Click Event Corresponding Function
pushShow(m){ // m is the received parameter
this.$router.push({
name:'xiangqing',
query:{
id:m.id,
title:m.title
}
})
}
replace View#
Button Passing Parameters
<button> @click="replaceShow(m)" push view</button>
Button Binding Click Event Corresponding Function
replaceShow(m){ // m is the received parameter
this.$router.replace({
name:'xiangqing',
query:{
id:m.id,
title:m.title
}
})
}
Difference:
- push view allows the browser to go back, there is a history record
- replace view will overwrite the browser's record, unable to go back normally
Forward and Backward#
Binding the following corresponding functions to buttons can achieve forward and backward
back(){ // Backward
this.$router.back()
}
forward(){ // Forward
this.$router.forward()
}
test(){
this.$router.go() // () inside is the number of steps to go forward, filling in a negative number will go back the corresponding number of steps.
}
Cache Route#
Function: Can prevent the loss of corresponding data when switching route components.
<keep-alive include="Component Name">
<router-view></router-view>
</keep-alive>
include The component names to be cached are filled in, if not filled, all route navigation will be cached by default.
<!-- Cache multiple route components -->
<keep-alive :include = "['News','Message']">
<router-view></router-view>
</keep-alive>
New Lifecycle Hooks#
Example: Flashing Text (Text with changing transparency over time)
Unique to route components
Written in the component
activated(){
// Activated when entering the component
},
deactivated(){
// Activated when leaving the component
}
Route Guards#
Requirement: Each route must have a name
Global Before Route Guard#
// This file is used to create the router for the entire application
import VueRouter from "vue-router";
// Import components
import MyHome from "../comments/home"
import MyAbout from "../comments/about"
// Create a router and export it
const router = new VueRouter({
routes: [
{
name: 'miao',
path: '/about',
component: MyAbout
},
{
name: 'cao',
path: '/home',
component: MyHome,
}
]
})
// Global before route guard
router.beforeEach((to, from, next) => { // Pass in parameters containing route information
// Called before switching routes each time, called during initialization
// to destination (target route); from source (currently located route); next release
// Check if the path to go is one of the two below, if so, release
if (to.path === '/home/news' || to.path === '/home/message') {
// Check if the value of school (key) in local storage is (ying), if so, release
if (localStorage.getItem('school') === 'ying') {
next()
}
}else{
alert('No permission to access') // If it does not meet the above conditions, prompt no permission to access
}
})
// Export router
export default router
meta:{}
can pass custom parameters (route source information)
// This file is used to create the router for the entire application
import VueRouter from "vue-router";
// Import components
import MyHome from "../comments/home"
import MyAbout from "../comments/about"
// Create a router and export it
const router = new VueRouter({
routes: [
{
name: 'miao',
path: '/about',
component: MyAbout,
meta: { pass: 'true' },// Permission indicator to determine whether to perform permission verification
},
{
name: 'cao',
path: '/home',
component: MyHome,
meta: { pass: 'false' }, // false according to the rules below cannot pass verification
}
]
})
// Global before route guard
router.beforeEach((to, from, next) => { // Pass in parameters containing route information
// Called before switching routes each time, called during initialization
// to destination (target route); from source (currently located route); next release
// Check if the path to go is one of the two below, if so, release
if (to.meta.pass) {
next()
} else {
alert('No permission to access') // If it does not meet the above conditions, prompt no permission to access
}
})
// Export router
export default router
Global After Route Guard#
// This file is used to create the router for the entire application
import VueRouter from "vue-router";
// Import components
import MyHome from "../comments/home"
import MyAbout from "../comments/about"
// Create a router and export it
const router = new VueRouter({
routes: [
{
name: 'miao',
path: '/about',
component: MyAbout,
meta: { pass: 'true', title: 'About' },
},
{
name: 'cao',
path: '/home',
component: MyHome,
meta: { pass: 'false', title: 'Home' },
}
]
})
// Global before route guard
router.beforeEach((to, from, next) => { // Pass in parameters containing route information
// Called before switching routes each time, called during initialization
// to destination (target route); from source (currently located route); next release
// Check if the path to go is one of the two below, if so, release
if (to.meta.pass) {
next()
} else {
alert('No permission to access') // If it does not meet the above conditions, prompt no permission to access
}
})
// Global after route guard
router.afterEach((to,from,next)=>{
// Called after switching routes each time, called during initialization
// Mainly used to modify the page title after jumping
document.title = to.meta.title || 'Meow Meow System'
})
// Export router
export default router
Exclusive Route Guard#
// This file is used to create the router for the entire application
import VueRouter from "vue-router";
// Import components
import MyHome from "../comments/home"
import MyAbout from "../comments/about"
// Create a router and export it
const router = new VueRouter({
routes: [
{
name: 'miao',
path: '/about',
component: MyAbout,
meta: { pass: 'true', title: 'About' },
},
{
name: 'cao',
path: '/home',
component: MyHome,
meta: { pass: 'false', title: 'Home' },
beforeEnter: (to, from, next) => {
// The usage is the same as the global route guard, only called before entering this component
}
}
]
})
// Global after route guard
router.afterEach((to,from,next)=>{
// Called after switching routes each time, called during initialization
// Mainly used to modify the page title after jumping
document.title = to.meta.title || 'Meow Meow System'
})
// Export router
export default router
Only before route guard without exclusive after route guard Route guards can be matched according to needs