Vue 2.0 Basic Details
- 2021-11-29 22:50:54
- OfStack
6.2 Routing Jump 6.3 Routing Guard 7, Status Manager Vuex7.1 Configuration 8, 5 Core Attributes 9, Http Request Library Axios
1. Characteristics
Is an MVVM framework
Derived from MVC architecture, it is divided into View (view layer), ViewModel (data view layer) and Model (data layer). The most iconic feature of MVVM is data binding, which realizes data-driven view and view synchronization of data.
Data is also unidirectional, which is called unidirectional data flow
Data is always passed from the parent component to the child component, and the child component does not have the right (not recommended) to modify the data in the parent component directly.
Incompatible with ie8 and browsers below
The responsive formula utilizes Object. defineProperty of es5, which does not support IE8
2. Examples
// Vue Single page instance
<template>
Label ...
</template>
<script>
export default {
data () {},
methods: {},
computed: {},
watch: {}
}
</script>
<style>
Style ...
</style>
3. Option Options
data
Function to define data for a page
data() {
return {
count: 2
copyCount: 1
}
}
// Use
this.count // 2
computed
Object, computed property, used to simplify complex logic processing
// Calculated attributes do not accept parameters, and will cache dependent data, which must have return
computed : {
doubleCount: function () {
return this.count *= 2
},
}
// Use
this.doubleCount // 4
methods
Object that defines the functions of the page
methods: {
cLog(msg) {
console.log(msg)
}
}
// Use
this.cLog(' The function was called ') // Console output: Function called
watch
Object and attribute listening, which is used to listen to the change of some data and make corresponding operations
watch: {
count(value, [oldValue]) {
// value The changed value
this.copyCount = value + 1
}
}
// When count Automatically triggered when a change occurs
this.count = 2
this.copyCount // 3
components
Object to register the component to the page
import UploadImg from 'xxxx'
components: { UploadImg }
// template
<upload-img>
4. Basic grammar
Commonly used instructions
v-html
Render HTML
v-if
Judge syntax, control show/hide, control by whether to render DOM or not
v-show
Control show/hide, similar to v-if, but v-show is controlled by display property
v-model
Bi-directional data binding, 1 generic for forms, default binding value property
v-bind
:
v-on
:
v-for
Traversal syntax that supports arrays, objects, and strings
5. Life cycle
beforeCreated
Creating an Vue object
created
data initialization, at which time you can do some pre-operation on the instance
beforeMounted
el and data initialization
v-if
0
Mount el and data, at which point the http request can be invoked
beforeUpdated
Before updating DOM, you can change the state in one step without triggering the re-rendering process
updated
: Update the modified virtual DOM to the page. Avoid changing operations at this time, so as not to cause infinite loop updates
beforeDestory
Before the page is destroyed, you can do some reset operations at this time, such as clearing the timer and dom events, etc.
destoryed
The page is destroyed, the Vue instance has been deleted, and all operations are invalid
6. Routing management Vue-Router
Official routing manager. It is deeply integrated with the core of Vue. js, making it easy to build single-page applications.
6.1 Routing Configuration
// NPM Download
npm install vue-router
// router.js
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
// Define Page Routing (Path, Component)
export default new Router({
{ path: '/foo', component: () => import('/pages/foo') }, // Lazy loading of routing components
{ path: '/bar', component: '/pages/bar'}
})
// main.js
import router from './router.js'
new Vue({
el: '#app',
router, // Mount routing to Vue Instances
render: h => h(App)
})
// page.vue
<!-- We should focus on distinguishing the relationship between the two -->
this.$router // Access router, built-in push , replace Routing method of
this.$route // Access the current route, built-in path , query Equal routing properties
// app.vue
<!-- The component to which the route matches will be rendered here -->
<router-view></router-view>
6.2 Routing Jump
Declarative routing
<router-link :to="...">
<router-link :to="..." replace>
Programmed routing
this.$router.push({ path: 'register', query: { plan: 'private' }})
this.$router.replace(...) // And push The difference is not inserting history Record
this.$router.go( [Number] n ) // In history How many steps forward or backward in the record
// It is recommended to use it first when routing parameters carry Chinese encodeURLComponent Transcode to avoid displaying garbled codes.
6.3 Routing Guard
Global guard
Valid for all configured routes, but with lower priority than internal routes.
Global front guard (commonly used)
// When a user fails to authenticate, redirect to /login
router.beforeEach((to, from, next) => {
// to The routing object to be entered, from Source routing, next Hook function, whether to release or not
if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
else next()
})
Global parsing guard (understand)
data() {
return {
count: 2
copyCount: 1
}
}
// Use
this.count // 2
0
Global rear hook (understand)
data() {
return {
count: 2
copyCount: 1
}
}
// Use
this.count // 2
1
Routing exclusive guard (understand)
This guard is only valid for configured routes, and the method parameters of these guards are identical to those of the global front guard.
data() {
return {
count: 2
copyCount: 1
}
}
// Use
this.count // 2
2
Component internal guard (understand)
The following routing navigation guards can be defined directly within the routing component, only for the current component.
beforeRouteEnter
beforeRouteUpdate (2.2 Add )
beforeRouteLeave
Guards in components | Vue-Router official documents
7. State Manager Vuex
7.1 Configuration
data() {
return {
count: 2
copyCount: 1
}
}
// Use
this.count // 2
4
8, 5 core attributes
state
Data source, do not directly modify state status
data() {
return {
count: 2
copyCount: 1
}
}
// Use
this.count // 2
5
mutations
The only way to change the state of state
data() {
return {
count: 2
copyCount: 1
}
}
// Use
this.count // 2
6
actions
Store asynchronous operation, asynchronously trigger mutation to change state
data() {
return {
count: 2
copyCount: 1
}
}
// Use
this.count // 2
7
getters
Data source processing, similar to calculating properties
const getter = {
formatName(state) {
return state.name + '2021'
}
}
<!--page.vue-->
// 1. Direct call
this.$store.getter.formatName() // 'xxx2021'
// 2. Auxiliary function mapping
computed: {
...mapGetters(['formatName'])
}
this.formatName() // // 'xxx2021'
modules
Modularization, allowing each module to manage its own set of state, mutations, actions and getters.
data() {
return {
count: 2
copyCount: 1
}
}
// Use
this.count // 2
9
modules | Vuex official document
9. Http Request Library Axios
Http request library based on promise encapsulation, officially recommended
<!-- api.js -->
import axios from 'axios'
// Creating and configuring instances
axios.create({
baseURL: 'http://www.baidu.com', // Request base address
timeout: 1000 // Request timeout
...
})
// Request interceptor
axios.interceptors.request.use(request => {
request.headers['Content-Type'] = 'application/json'
...
})
// Response interceptor
axios.interceptors.response.use(response => {
...
return response.data
})
// Configuration request
export default {
getId: () => axios.get('/getId'),
getNameById: id => axios.post('/getNameById', id)
}
<!-- main.js -->
import api from './api.js'
Vue.prototype.$api = api
<!-- page.vue -->
this.$api.getId().then(res => {
...
}).catch()