vue添加拦截器(身份认证)以及cookie认证

vue

一、安装vuex和cookies

npm install vuex --save

npm install vue-cookies --save

在全局变量文件中引用

import Vue from \'vue\'

import Vuex from \'vuex\'

import Cookie from \'vue-cookies\'

Vue.use(Vuex);

export default new Vuex.Store({

state: {

username: Cookie.get("username"),

token: Cookie.get("token"),

},

mutations: {

saveToken: function (state, userToken) {

state.username = userToken.username;

state.token = userToken.token;

Cookie.set("username", userToken.username, "20min");

Cookie.set("token", userToken.token, "20min")

},

clearToken: function (state) {

state.username = null;

state.token = null;

Cookie.remove("username");

Cookie.remove("token");

// this.$router.push({name: "micro"});

},

}

})

二、在vue文件中将登陆数据存入cookie

创建出发事件:

<button @click="toLogin">提交</button>

创建触发的方法

methods:{

toLogin(){

var that = this;

this.$axios.request({

url: "http://127.0.0.1:8000/api/v1/auth/",

method: "POST",

data: {username: this.username, password: this.password},

headers: {

"Content-Type":"application/json",

"k1":"v1",

}

}).then(function (arg) {

if (arg.data.code === 1000){

console.log(arg.data);

// that.$store.state.token = arg.data.token;

// that.$store.state.username = that.username;
         // 第一个参数saveToken为这里调用的全局变量文件中定义的方法,第二个参数为传入的变量

that.$store.commit("saveToken",{"username": that.username,"token":arg.data.token});

}else {

console.log(arg.data)

}

}).catch(function () {

console.log("请求失败!")

})

}

}

三、首页中如何判断cookie中是否含有用户token

<div v-if="this.$store.state.token">

<a>{{this.$store.state.username}}</a>

<a @click="logout">注销</a>

</div>

<div v-else>

<router-link to="/login">登陆</router-link>

</div>

四、在路由文件中添加认证

index.js文件中

{

path: \'/micro\',

name: \'micro\',

component: Micro,

meta:{

"requireAuth": true,

}

在main.js中

router.beforeEach(function (to, from, next) {

if (to.meta.requireAuth){

if (store.state.token){

next()

}else {

next({name: "login",query:{backUrl:to.fullPath}})

}

} else {

next()

}

});

配置后,如果登陆成功,应该自动进入想要进入的页面,需要在toLogin()方法中加入刷新页面的功能

var url = that.$route.query.backUrl;

// console.log(url)

if (url){

that.$router.push({path:url})

}else {

that.$router.push({path:"index"})

}

五、页面加载后,自动向后端提交token

methods: {

initMicro(){

var that = this;

this.$axios.request({

url: "http://127.0.0.1:8000/api/v1/micro/",

method: "GET",

params: {

token: this.$store.state.token,

}

}).then(function (ret) {

if (ret.data.code === 1000){

that.micro_title = ret.data.data

}

})

}

}

后端接收到token后,从数据库查询,如果能够获取结果,则返回正确的值和数据,取出数据后,即可渲染模板。

以上是 vue添加拦截器(身份认证)以及cookie认证 的全部内容, 来源链接: utcz.com/z/374770.html

回到顶部