vue-router+axios+vuex大雜燴

vue-router

1.vue-router路由基本加載

簡單四步走javascript

  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參數html

獲取name參數以下vue

//在跳轉的那個組件取獲取
let name = this.$route.params.name;//注意$route主要用來獲取參數,$router用來執行方法
複製代碼
  1. get取參java

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

    獲取傳參:let name = this.$route.query.nameios

4.編程式導航

$router用來執行方法vue-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. 動態路由vuex

    路由shell

{
	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. 非動態路由npm

    路由

{
   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{
    //在進入頁面前執行,
    beforeRouterEnter(to,from,next){
		console.log(from.name);
        next();
        //這裏不能直接獲取組件實例
        //要獲取須要使用next
        next(vm=>{
            console.log("這是組件的實例:"+vm)
        })
    },
    // 在離開頁面時執行,
    afterRouterLeave(to,from,next){
        const leave = confirm('您肯定要離開嗎?');
        if(leave) next()//點擊肯定則離開
        else next(false)
    }
	// url 發生變化,而且組件複用時調用,通常是動態路由
    beforeRouterUpdate(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,若是要轉載,請註明出處,

若是以爲寫的不錯, 請點個贊吧

相關文章
相關標籤/搜索