在Vue中如何使用Cookie操作实例

2020-06-12 21:22:53易采站长站整理

</el-form-item>
<el-form-item prod="u_password">
<el-input type="password" v-model="account.u_password" auto-complete="off" placeholder="请输入密码"></el-input>
</el-form-item>
<el-form-item style="width:100%;">
<el-button type="primary" style="width:100%" @click="handleLogin" :loading="logining">登录</el-button>
</el-form-item>
</el-form>
</template>

<script>
export default {
data() {
return {
logining: false,
account: {
u_telephone:'',
u_password:''
},
//表单验证规则
rules: {
u_telephone: [
{required: true, message:'请输入账号',trigger: 'blur'}
],
u_password: [
{required: true,message:'请输入密码',trigger: 'blur'}
] }
}
},
mounted() {
//初始化
},
methods: {
handleLogin() {
this.$refs.AccountFrom.validate((valid) => {
if(valid) {
this.logining = true;
//其中 'm/login' 为调用的接口,this.account为参数
this.$post('m/login',this.account).then(res => {
this.logining = false;
if(res.errCode !== 200) {
this.$message({
message: res.errMsg,
type:'error'
});
} else {
let expireDays = 1000 * 60 * 60 ;
this.setCookie('session',res.errData.token,expireDays); //设置Session
this.setCookie('u_uuid',res.errData.u_uuid,expireDays); //设置用户编号
if(this.$route.query.redirect) {
this.$router.push(this.$route.query.redirect);
} else {
this.$router.push('/home'); //跳转用户中心页
}
}
});
} else {
console.log('error submit');
return false;
}
});
}
}
}
</script>

五、在路由中验证token存不存在,不存在的话会到登录页

在 router–index.js中设置路由,代码如下:


import Vue from 'vue'
import Router from 'vue-router'
import {post,fetch,patch,put} from '@/util/http'
import {delCookie,getCookie} from '@/util/util'

import Index from '@/views/index/Index' //首页
import Home from '@/views/index/Home' //主页
import right from '@/components/UserRight' //右侧
import userlist from '@/views/user/UserList' //用户列表
import usercert from '@/views/user/Certification' //用户审核
import userlook from '@/views/user/UserLook' //用户查看
import usercertlook from '@/views/user/UserCertLook' //用户审核查看

import sellbill from '@/views/ticket/SellBill'
import buybill from '@/views/ticket/BuyBill'
import changebill from '@/views/ticket/ChangeBill'