nuxt.config.js配置
modules: [
'cookie-universal-nuxt',
],
store目录新建index.js
export const state = {
token:''
}
export const mutations = {
setToken(state,token){
state.token = token;
this.$cookies.set('token',token)
},
getToken(state){
state.token = this.$cookies.get('token');
}
}
login.vue
<template>
<div>
账号:<input v-model="username" placeholder="请输入内容">
密码:<input v-model="password" placeholder="请输入内容">
<button @click='login'>信息按钮</button>
</div>
</template>
<script>
import {mapMutations} from 'vuex'
export default{
data(){
return {
username:'',
password:''
}
},
methods:{
...mapMutations(['setToken']),
login(){
let data = {
username : this.username,
password : this.password,
loginType : 2
}
this.$axios({
url:'/api/user/login',
method:'post',
data
}).then(res => {
this.setToken(res.data.accessToken)//获取Token
this.$router.push({name:'index'})
})
}
}
}
</script>
判断其他页面是否登录有token,如果没有,则调到登录页面
增加一个中间件 新增middleware目录增加一个auth.js文件
<script>
export default{
middleware:'auth',
}
</script>
middleware目录下auth.js
export default function({store,route,redirect,params,query}){
store.commit('getToken')
if(!store.state.token){//如果没有获取到token则转向另一个页面
redirect('/login');//改变方向redirect
}
}