vue Cookies
安装cookie
"dependencies": { "axios": "^0.18.0", "element-ui": "^2.4.11", "font-awesome": "^4.7.0", "js-cookie": "^2.2.0", "vue": "^2.5.2", "vue-i18n": "^8.7.0", "vue-router": "^3.0.1" },
<script> import mock from '@/mock/index.js' import Cookies from "js-cookie" import router from '@/router' export default { name: 'Login', methods: { login() { this.$api.login.login().then(function(res) { alert(res.data.token) Cookies.set('token', res.data.token) // 放置token到Cookie router.push('/') // 登录成功,跳转到主页 }).catch(function(res) { alert(res); }); } } } </script>
存入,在登录的时候
import Cookies from "js-cookie"
Cookies.set('token', res.data.token)
获取,路由跳转的时候
import Cookies from "js-cookie";
// request 请求拦截器 instance.interceptors.request.use( config => { let token = Cookies.get('token') // 发送请求时携带token if (token) { config.headers.token = token } else { // 重定向到登录页面 router.push('/login') } return config },