「Vue」登錄-路由攔截器

一、main.js設置攔截器vue

router.beforeEach(function (to,from,next) {
  if (to.meta.requireAuth) {
    if (store.state.token) {
      next()
    } else {
      next({name: 'log',query: {backUrl: to.fullPath}})
    }
  }else(
    next()
  )
})
View Code

二、路由設置ios

{ path: '/course',component: Course,meta: { requireAuth: true}}

三、vue頁面方法設置,對應main.js設置的backUrlaxios

login() {
            this.$axios.post('api/login/',{user:this.user,pwd:this.pwd}).then(ret => {
                if (ret.data.code === 1000) {
                    var obj = {token:ret.data.token,name:ret.data.data}
                    this.$store.commit('getToken',obj)
                    var url = this.$route.query.backUrl
                    if (url) {
                        this.$router.push({path: url})
                    } else {
                        this.$router.push({name:'home'})
                    }
                    
                }
                if (ret.data.code === 1001) {
                    alert('用戶名或密碼錯誤')
                }
                if (ret.data.code === 1002) {
                    alert('請求錯誤')
                }
            }).catch(ret => {
                console.log(ret)
            })
            this.user = ''
            this.pwd = ''
            
        }
View Code
相關文章
相關標籤/搜索