vue-router+axios+vuex大杂烩

3,504 阅读3分钟

vue-router

1.vue-router路由基本加载

简单四步走

  1. 安装
npm install --save vue-router
或者
vue add router
  1. 引用
import router from 'vue-router'
Vue.use(router)
  1. 配置路由文件,并在vue实例中注入
var rt = new router({//以一个对象的形式传入参数
   routes:[//数组形式,
       {
           path:'/',//指定要跳转的路径
           compoent:HelloWorld//指定要展示的组件
        //以下部分可以跳过   
           name:'helloworld'//指定该路径名称,:to="{name:“helloworld”}"//必须唯一
           children:[//嵌套路由的子路由
            {
                path:"child",// 这里不要在前面加/,
                component:() => import('./views/child.vue')//懒加载的方式
            }
           ],
           redirect:'/',//重定向
           alias:"/home";//别名,即访问“/”和“/home”跳转到同一个页面
           mode:'history';//默认为hash模式,在url上会加个#,比较难看,一般采用‘history’
       } 
   ]
})

//在vue中注入实例
new Vue({
el:"#app",
   router:rt,
   components:{App},
   template:'<App/>'
})
  1. 确定视图加载的位置
<router-view></router-view>

2.路由的跳转

<router-link :to="{name:'helloworld'}"></router-link>//加`:`双引号里面的是js表达式
<router-link to="/hello"></router-link>不加`:`双引号里面的是是字符串

3.router传参数

  1. 动态路由
routes:[{
   path:"/home/:name",
   name:"home",
   component:home,
}]

<router-link :to="{name:'home',params:{name:'胡志武'}}"></router-link>
//等同
url:'http://loacalhost:8080/home/胡志武'

无论/home/后面是什么,都会进入到home页面,而后面的内容会被映射成name参数

获取name参数如下

//在跳转的那个组件取获取
let name = this.$route.params.name;//注意$route主要用来获取参数,$router用来执行方法
  1. get取参

    url:http://loacalhost:8080/home?name=胡志武

    获取传参:let name = this.$route.query.name

4.编程式导航

$router用来执行方法

// 字符串,这里的字符串是路径path匹配噢,不是router配置里的name
this.$router.push('/home')

// 对象
this.$router.push({ path: '/home' })

// 命名的路由 这里会变成 /user/123
this.$router.push({ name: 'user', params: { userId: 123 }})

// 带查询参数,变成 /home?name='胡志武'
this.$router.push({ path: '/home', query: { name: '胡志武' }})

// 回退到上一个历史记录
this.$router.go(-1);

this.$router.back();

//	重定向,用新的路径代替旧的历史记录
this.$router.replace('/home')

5.命名视图

<router-view name="main"/>//这里name不是路由的name而是组件的name

//上面的视图对应下面的路由
{
	path:"/home",
	name:"home",
	components:{//注意这里是components,
		main:()=>import(‘@/home.vue’)
	}
}

6.路由组件传参

  1. 动态路由

    路由

{
	path:'home/:name',
     component:()=>import("@/home.vue"),
     props:true,//这里要写true,表明可以传参给组件
}
     //还可以用路由编程的方法
{
    props:route=>({
        name:route.params.name
    })
}
   home组件
// 这是没有使用路由组件传参的写法
<div>{{$route.params.name}}</div>

// 这是路由组件传参的写法
<div>{{name}}</div>

export default {
   props:{
       name:{
           type:String,
           default:'胡志武‘
       }
   }
}

  1. 非动态路由

    路由

{
   path:'/home',
   name:'home',
   component:()=>import("@/home.vue"),
   props:{
         name:"胡志武"
    }
}

   home组件
<div>
   {{name}}
</div>


export default{
props:{
       name:{
        type:String,
        default:'hzw'
       }
	}
}

7.导航守卫

router.js----全局导航守卫

const LOGINED = true;//登录状态是true
//全局前置守卫。就是在真正进入另一个页面前触发
router.beforeEach((to,from,next)=>{
    //to和from都是路由对象
    //to是你即将跳转的路由对象
    //from是你即将离开的路由对象
    //next 决定路由跳转到哪里
    if(to.name!=='login'){
        //如果页面跳转的不是登录页面
        //判断其登录状态,登录了才能跳转
        if(LOGINED) next()//next(里面什么都没有则跳转到to的页面),
        else next({name:'login'})//没有登录则,跳转到登录页面
    }else{
        if(LOGINED) next({name:"home"})//已经登录了,就直接去主页
        else next();//没有登录去login页面
    }
})

//后置钩子,路由跳转成功后触发
router.afterEach((to,from)=>{
    //	这个用来关闭loding动画是最好的了
})

路由独享守卫

{
    path:"/",
    component:home,
        //在进入这个页面前会判断
    beforeEnter:(to,from,next)=>{
    	if(from.name=='login') alert('从登录页面来')
        else alert('这不是从登录页面来的')
        
        next();//这里一定腰写next,不然路由会跳转失败
    }
}

组件内守卫

export default{
    //在进入页面前执行,
    beforeRouteEnter(to,from,next){
		console.log(from.name);
        next();
        //这里不能直接获取组件实例
        //要获取需要使用next
        next(vm=>{
            console.log("这是组件的实例:"+vm)
        })
    },
    // 在离开页面时执行,
    afterRouteLeave(to,from,next){
        const leave = confirm('您确定要离开吗?');
        if(leave) next()//点击确定则离开
        else next(false)
    }
	// url 发生变化,并且组件复用时调用,一般是动态路由
    beforeRouteUpdate(to,from,next){
        //因为已经在页面内了,所以这里可以用this,this指向当前组件的实例
		console.log(to.name,from.name)
    }
}

8.路由元信息

这个可以用来改变每个页面中的title属性

路由

{
    path:"/",
    component:()=>import('@/home.vue'),
    meta:{
    	title:'首页'        
    }
}

全局导航守卫

router.beforeEach((to,from,next)=>{
    to.meta && setTitle(to.meta.title)
})

setTitle(title){
    window.document.title = title || '你好'
}

Axios的使用

axios的简介: axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征:

  • 从浏览器中创建 XMLHttpRequest
  • 从 node.js 发出 http 请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求和响应数据
  • 取消请求
  • 自动转换JSON数据
  • 客户端支持防止 CSRF/XSRF

1. 使用axios三步走

  1. 安装

    npm install axios
    
  2. 引入加载

    import axios from 'axios'
    
  3. 将axios全局挂载到VUE原型上

    这一步是为了方便全局使用

    import Vue from 'vue'
    Vue.prototype.$http = axios;
    

2.axios get请求

axios.get("/user?ID=12345")
    .then(function(res){//成功执行的函数
    	console.log(res)
	})
    .catch(function(err){//失败执行的函数
    	console.log(err);
	})

上面的请求还可以这样子写

axios.get('/user',{
    params:{
        ID:12345
    }
})
    .then(function(res){
    	console.log(res)
	})
    .catch(function(err){
    	console.log(err);
	})

3.axios post请求

axios.post("/user",{
    firstName:'志武',
    lastName:"胡"
})
    .then(function(res){
    	console.log(res);
	})
    .catch(function(err){
    	console.log(err)
	})

post传递数据有两种格式:

  • form-data?page=1&limit=48
  • x-www-form-urlencoded {page:1,limit:10}

在axios中,post请求接收的参数必须是form-data

qs插件,qs.stringify

npm i -S qs

import qs from 'qs'

axios.post("/user",qs.stringify({
    firstName:'志武',
    lastName:"胡"
}))
    .then(function(res){
    	console.log(res);
	})
    .catch(function(err){
    	console.log(err)
	})

Vuex的相关操作

vuex是用来管理状态,共享数据,在各个组件之间管理外部状态

1. 使用Vuex四步走:

  1. 引入vuex,并通过use方法使用它
import Vuex from 'vuex',
import Vue from 'vue',
Vue.use(Vuex)
  1. 创建状态仓库
//注意Store,state不能改
var store = new Vuex.Store({
   state:{
       name:"胡志武"
   }
})
  1. 挂载到根组件的实例上
new Vue({
    router,
    store,
    ...
})
  1. 通过this.$store.state.name直接拿到需要的数据

2. vuex状态管理流程

view ---> actions ---> mutations ---> state ---->view

3. Vuex怎么改变状态

  1. mutations直接改变state的数据
var store = new Vuex.Store({
    state:{
        name:"胡志武"
    },
    mutations:{
    //这里传入的是state	
		change(state){
			state.name="志武胡"
		}
})


//调用
this.$store.commit('change')//这里传入的是你要调用的函数的名字
  1. actions通过mutation来改变状态,而不是直接改变状态

    actions内部可以有异步操作,而mutations不行

var store = new Vuex.Store({
    state:{
        name:"胡志武"
    },
    mutations:{
    //这里传入的是state	
		change(state){
			state.name="志武胡"
		}
	},
    actions:{
        //这里传入的是上下文
         actionChange(context){
             context.commit('change')
          }
    }
)

//如何调用
this.$store.dispatch('actionChange')
  1. getters 获取状态的同时,进行判断
var store = new Vuex.Store({
    state:{
        name:"胡志武"
    },
    mutations:{
    //这里传入的是state	
		change(state){
			state.name="志武胡"
		}
	},
    actions:{
        //这里传入的是上下文
         actionChange(context){
             context.commit('change')
          }
    },
    getters:{
        getName(state){
            return state.name===''?'胡志武':state.name
        }        
    
//调用
this.$store.getters.getName
)
  1. Vuex的模块里的状态
new Vuex.Store({
    modules:{
        user:{
            state:{
                admin:'胡志武'
            },
            mutations:{},
            ...
        }
    }
})
// 如何访问
    this.$store.state.user.admin

结语

因为本人水平有限,如果有错漏的地方,还请看官多多指正

本文作者胡志武,写于2019/5/24,如果要转载,请注明出处,

如果觉得写的不错, 请点个赞吧