axios novice practice to achieve landing

In fact, such as the Internet has been a lot of good articles, writing this article is to be the equivalent of notes in case you forget the
use of: 1, vuex 2, axios 3 , vue-route

Login process: 1, submit the login form, to get the data back to return the
2, the data stored in vuex

1, vuex configuration

Here skip installing the like, Baidu a lot, I directly on the code

// store index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
// 初始化时用sessionStore.getItem('token'),这样子刷新页面就无需重新登录
const state = {
  user: window.sessionStorage.getItem('user'),
  token: window.sessionStorage.getItem('token')
}
const mutations = {
  //将token保存到sessionStorage里,token表示登陆状态
  SET_TOKEN: (state, data) => {
    state.token = data
    window.sessionStorage.setItem('token', data) 
  },
  //获取用户名
  GET_USER: (state, data) => {
    // 把用户名存起来
    state.user = data
    window.sessionStorage.setItem('user', data)
  },
  //登出
  LOGOUT: (state) => {
    // 登出的时候要清除token
    state.token = null
    state.user = null
    window.sessionStorage.removeItem('token')
    window.sessionStorage.removeItem('user')
  }
}

const actions = {
}
export default new Vuex.Store({
  state,
  mutations,
  actions
})

(1) I am here to login token status, and user name user sessionStorage exist in order to use the component, if the token is true it means that the user is logged sessionStorage and token two things very simple use of self-Baidu
(2) Do not forget introduction store in main.js, vue instances have added store
main.js

import store from './store/index'

new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

2, vue-route configuration

import Vue from 'vue'
import Router from 'vue-router'
import Login from '../components/Login'
import Activity from '../components/Activity'
import Index from '../components/Index'
import store from '../store/index'

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/',
      name: '/',
      component: Index
    },
    {
      path: '/login',
      name: 'login',
      component: Login
    },
    {
      path: '/activity',
      name: 'activity',
      component: Activity,
      meta: {
        requireAuth: true // 添加该字段,表示进入这个路由是需要登录的
      }
    }
  ]
})
// 注册全局钩子用来拦截导航
router.beforeEach((to, from, next) => {
  const token = store.state.token
  if (to.meta.requireAuth) { // 判断该路由是否需要登录权限
    if (token) { // 通过vuex state获取当前的token是否存在
      next()
    } else {
      console.log('该页面需要登陆')
      next({
        path: '/login'
        // query: {redirect: to.fullPath} // 将跳转的路由path作为参数,登录成功后跳转到该路由
      })
    }
  } else {
    next()
  }
})

export default router

Here I used router.beforeEach to achieve interception landing,
1, join in our own requireAuth need to verify the routing of meta in
2, router.beforeEach in by requireAuth verify that the components need to be logged
3, verification token if it means flase No landing jumps to the login page

3, axios transmission request

submitLogin () {
  this.$refs.loginForm.validate(valid => {
    if (valid) {
      axios.post('/login', {
        user: this.loginForm.user,
        pass: this.loginForm.pass
      })
        .then((response) => {
          if (response.status === 200) {
            this.$store.commit('SET_TOKEN', response.data.token)
            this.$store.commit('GET_USER', response.data.user)
            this.$message({
              message: '登陆成功',
              type: 'success'
            })
            this.$router.push({name: 'activity'})
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    } else {
      console.log('error submit!!')
      return false
    }
  })
},

I did not write back, with mock.js intercept ajax request
because I use the element-ui so there is some direct disregard the above code, look at the core of the line
1, returns after successful data with the this. \ (To update store.commit vuex in the data 2, after the successful landing jump the this \). router.push () jump page,
here note that if you intercept a hook in front of navigation with the query: {redirect: to.fullPath}, then
here with the this. \ (router.push (the this \). route.query.redirect); so you can jump to the page
you jump to that route to go to the front landing page

TOKEN here that I did not use, is bring this TOKEN when the requested page, and back-end verification.

Guess you like

Origin www.cnblogs.com/zyh0430/p/12002730.html