vue-router
1. Vue-router routes are loaded
Four simple steps
- The installation
NPM install --save vue-router or vue add routerCopy the code
- reference
import router from 'vue-router'
Vue.use(router)
Copy the code
- Configure the routing file and inject it into the VUE instance
var rt = new router({// Pass the argument as an object
routes:[// Array,
{
path:'/'.// Specify the path to jump to
compoent:HelloWorld// Specify the component to display
// The following parts can be skipped
name:'helloworld'// Specify the path name, :to="{name: "helloWorld"}"// Must be unique
children:[// The child path of nested routines
{
path:"child".// Don't put a/in front of it,
component:(a)= > import('./views/child.vue')// Lazy loading mode}].redirect:'/'./ / redirection
alias:"/home";// Alias, that is, access "/" and "/home" to jump to the same page
mode:'history';// Default hash mode, add a # to the URL, which is ugly, usually use 'history'}]})// Inject the instance into vue
new Vue({
el:"#app".router:rt,
components:{App},
template:'<App/>'
})
Copy the code
- Determine where the view is loaded
<router-view></router-view>
Copy the code
2. Route forwarding
<router-link :to="{name:'helloworld'}"></router-link>// add ':' double quotes inside the js expression<router-link to="/hello"></router-link>Without the ':' double quotes inside is a stringCopy the code
3. The router parameters
- Dynamic routing
routes:[{
path:"/home/:name".name:"home".component:home,
}]
<router-link :to="{name:'home',params:{name:' hu Zhiwu '}}"></router-link>/ / equivalent url: 'http://loacalhost:8080/home/ zhi-wu hu'Copy the code
Whatever comes after /home/is going to go to the home page, and that’s going to be mapped to the name parameter, okay
Get the name argument as follows
// Fetch at the component of the jump
let name = this.$route.params.name;// Note that $route is used to get parameters, and $router is used to execute methods
Copy the code
-
Get to take the cords
url:http://loacalhost:8080/home? Name = zhi-wu hu
Let name = this.$route.query.name
Programmatic navigation
$router is used to execute the method
// String, the string is the path matching the router configuration, not the name
this.$router.push('/home')
/ / object
this.$router.push({ path: '/home' })
// The named route becomes /user/123
this.$router.push({ name: 'user'.params: { userId: 123 }})
// With query parameters, change to /home? Name =' Hu Zhiwu '
this.$router.push({ path: '/home'.query: { name: 'Hu Zhiwu' }})
// Go back to the previous record
this.$router.go(- 1);
this.$router.back();
// Redirect to replace the old history with a new path
this.$router.replace('/home')
Copy the code
5. Name the view
<router-view name="main"/>{path:"/home", name:"home", components:{// Note that components, The main () = > import (' @ / home. Vue ')}}Copy the code
6. Route components send parameters
-
Dynamic routing
routing
{
path:'home/:name'.component:(a)= >import("@/home.vue"),
props:true.// Write true to indicate that you can pass the parameter to the component
}
// You can also use routing programming
{
props:route= >({
name:route.params.name
})
}
Copy the code
Home componentsCopy the code
// This is written without using the route component to pass parameters<div>{{$route.params.name}}</div>// This is the route component to write the parameter<div>{{name}}</div>Export default {props:{name:{type:String, default:' Props'}}Copy the code
-
Non-dynamic routing
routing
{
path:'/home'.name:'home'.component:(a)= >import("@/home.vue"),
props: {name:"Hu Zhiwu"}}Copy the code
Home componentsCopy the code
<div>
{{name}}
</div>
export default{
props:{
name:{
type:String,
default:'hzw'
}
}
}
Copy the code
7. Navigation Guard
Router.js —- Global navigation guard
const LOGINED = true;// The login status is true
// Global front-guard. It's triggered right before you actually go to another page
router.beforeEach((to,from,next) = >{
// To and FROM are both routing objects
// To is the route object to which you are going to jump
// From is the route object you are leaving
// Next decides where to route to
if(to.name! = ='login') {// If the page is not the login page
// Check the login status, login can jump
if(LOGINED) next()//next(if there is nothing in it, jump to the to page),
else next({name:'login'})// If there is no login, go to the login page
}else{
if(LOGINED) next({name:"home"})// If you have logged in, go directly to the home page
else next();// There is no login to the login page}})// Redirects the route successfully
router.afterEach((to,from) = >{
// This is best used to turn off loding animation
})
Copy the code
Route exclusive guard
{
path:"/".component:home,
// Will be judged before entering the pageBeforeEnter: (to,fromAnd next) = > {if(from.name=='login') alert('From the login page')
else alert('This is not from the login page.')
next();// Write next, otherwise the route will fail to jump}}Copy the code
Component internal guard
export default{
// Execute before entering the page,
beforeRouteEnter(to,from,next){
console.log(from.name);
next();
// You can't get the component instance directly here
// To get this, use next
next(vm= >{
console.log("Here is an instance of the component:"+ vm)})},// Execute when leaving the page,
afterRouteLeave(to,from,next){
const leave = confirm(Are you sure you want to leave? ');if(leave) next()// Click OK to leave
else next(false)}// called when the URL changes and the component is reused, usually dynamic routing
beforeRouteUpdate(to,from,next){
// Since it is already in the page, we can use this, which refers to the instance of the current component
console.log(to.name,from.name)
}
}
Copy the code
8. Route meta information
This can be used to change the title property on each page
routing
{
path:"/".component:(a)= >import('@/home.vue'),
meta: {title:'home'}}Copy the code
Global navigation guard
router.beforeEach((to,from,next) = >{
to.meta && setTitle(to.meta.title)
})
setTitle(title){
window.document.title = title || 'hello'
}
Copy the code
The use of Axios
About AXIos: Axios is an HTTP client based on Promises for browsers and NodeJS, which itself has the following features:
- Create an XMLHttpRequest from the browser
- Make HTTP requests from Node.js
- Supporting Promise API
- Intercept requests and responses
- Transform request and response data
- Cancel the request
- Automatically convert JSON data
- The client supports CSRF/XSRF prevention
1. Use Axios in three steps
-
The installation
npm install axios Copy the code
-
Introduction of loading
import axios from 'axios' Copy the code
-
Mount AXIos globally to the VUE prototype
This step is for global use
import Vue from 'vue' Vue.prototype.$http = axios; Copy the code
2. Axios get request
axios.get("/user? ID=12345")
.then(function(res){// Successfully executed function
console.log(res)
})
.catch(function(err){// Failed to execute the function
console.log(err);
})
Copy the code
The above request could have been written like this
axios.get('/user', {params: {ID:12345
}
})
.then(function(res){
console.log(res)
})
.catch(function(err){
console.log(err);
})
Copy the code
3. Axios post request
axios.post("/user", {firstName:'chi wu', lastName:"Hu"
})
.then(function(res){
console.log(res);
})
.catch(function(err){
console.log(err)
})
Copy the code
Post passes data in two formats:
- form-data? page=1&limit=48
- x-www-form-urlencoded {page:1,limit:10}
In AXIos, the argument received in the POST request must be form-data
Qs plugin, qs.stringify
npm i -S qs
import qs from 'qs'
axios.post("/user",qs.stringify({
firstName:'chi wu', lastName:"Hu"
}))
.then(function(res){
console.log(res);
})
.catch(function(err){
console.log(err)
})
Copy the code
Vuex operations
Vuex is used to manage state, share data, and manage external state between components
1. Use Vuex in four steps:
- Introduce the vuex and use it with the use method
import Vuex from 'vuex'.import Vue from 'vue',
Vue.use(Vuex)
Copy the code
- Create a state store
// Note that Store state cannot be changed
var store = new Vuex.Store({
state: {name:"Hu Zhiwu"}})Copy the code
- Mount to an instance of the root component
new Vue({
router,
store,
...
})
Copy the code
- Call this.$store.state.name to retrieve the required data
Vuex status management process
view —> actions —> mutations —> state —->view
3. How does Vuex change its state
- Mutations directly change state’s data
var store = new Vuex.Store({
state: {name:"Hu Zhiwu"}, mutations: {// State is passed in
change(state){
state.name="Chi Wu Hu"}})/ / call
this.$store.commit('change')// This is the name of the function you want to call
Copy the code
-
Actions changes state by mutation, rather than changing state directly
Actions can have asynchronous operations inside, but mutations cannot
var store = new Vuex.Store({
state: {name:"Hu Zhiwu"}, mutations: {// State is passed in
change(state){
state.name="Chi Wu Hu"}},actions: {// The context is passed in
actionChange(context){
context.commit('change')}})// How to call
this.$store.dispatch('actionChange')
Copy the code
- Getters gets the state and makes a judgment
var store = new Vuex.Store({
state: {name:"Hu Zhiwu"}, mutations: {// State is passed in
change(state){
state.name="Chi Wu Hu"}},actions: {// The context is passed in
actionChange(context){
context.commit('change')}},getters:{
getName(state){
return state.name===' '?'Hu Zhiwu':state.name
}
/ / call
this.$store.getters.getName
)
Copy the code
- Vuex module status
new Vuex.Store({
modules: {user: {state: {admin:'Hu Zhiwu'
},
mutations: {},... }}})// How to access
this.$store.state.user.admin
Copy the code
conclusion
Because my level is limited, if there are mistakes and omissions, please see more corrections
This article was written by Hu Zhiwu on 2019/5/24. If you want to reprint it, please indicate the source.
If you think it’s good, please give it a thumbs up