• Wechat mini program mpvue+vantUI+ Flyio +vuex into the pit (1)
  • Wechat mini program mpvue+vantUI+ Flyio +vuex into the pit (2)

After a long time to update, one is quite busy, and is not know what to introduce, recently a small partner asked me, how to authentication and so on, I will share my authentication.

The project structure

First look at the project structure

├ ─ ─ the build# webpack file, configuration parameters, packaged code stored here.├ ─ ─ the configThe basic configuration file for the vue project├ ─ ─ node_modulesDependencies installed in the project├ ─ ─ the SRC# source code folder└ ─ ─ APIRequest interface file└ ─ ─ the components# Place individual VUE component files└ ─ ─ pages# Each page file└ ─ ─ storeProject status management file, including login, user information and token, etc└ ─ ─ style# Project public style└ ─ ─ utils# project public js file└ ─ ─ app. Json# Applet app.json└ ─ ─ App. Vue# app.vue component, project entry file└ ─ ─ the main jsThe core entry file for the project├ ─ ─ the staticStatic resource directory, such as images, fonts, etc└ ─ ─ images# Login encryption profile├ ─ ─ babelrcVue development requires Babel compilation├ ─ ─ editorconfigEdit the environment configuration file├ ─ ─ eslintignore# eslint checks ignored files├ ─ ─. Eslintrc. Js# eslint checks configuration files├ ─ ─ gitignoreGit ignores files├ ─ ─. Postcssrc. Js# CSS configuration file, automatically complete the browser CSS prefix├ ─ ─ index. HTML# Home page, project entry file├ ─ ─ package. JsonProject profile, which describes project information and dependencies├ ─ ─ the README, mdProject description document, Markdown format
Copy the code

The use of Vuex

First, install vuex

npm install vuex -S
Copy the code

Create the store

Once the Store directory is created, use Vuex just like a normal VUE project

import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
Vue.use(Vuex)

const store = new Vuex.Store({
  modules: {
    user
  },
  state: {
    count: 0
  },
  mutations: {
    increment: (state) => {
      const obj = state
      obj.count += 1
    },
    decrement: (state) => {
      const obj = state
      obj.count -= 1
    }
  }
})

export default store
Copy the code

Mount store to Vue

Configure what to do for state management

My token information is stored in the user, the use of small program storage to do persistent

const user = {
  state: {
    token: mpvue.getStorageSync('token'),
    userinfo: mpvue.getStorageSync('user')
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USER: (state, user) => {
      state.userinfo = user
    }
 }
}
Copy the code

$store.state.user.token = $store.state.user.token = $store.state.user.token = $store.state.token = $store.state.user.token = $store.state.token = $store.state.token = $store.state.token This.$store.state.user.token is also available in js. MapState is also available

import { mapState } from 'vuex'

exportdefault { computed: { ... mapState({ userinfo: state => state.user.userinfo }) } }Copy the code

Configure apiconfig to request data authentication

Let’s first introduce store

import store from '@/store'
Copy the code

Request to intercept

Intercepting requests, as we talked about earlier in flyio

/ / add request interceptor fly. Interceptors. Request. Use (config = > {const token = store. State. The user. The token. / / the console log (token) / / Add custom header config.headers[to all requests'token'] = token
  if (config.headers['Content-Type']! = ='application/json') {config.body = qs.stringify(config.body)} // The interceptor returns Request by default if there is no return valuereturn config
}, error => {
  Promise.reject(error)
})
Copy the code

Authentication interception of the response

If the token is invalid at this time, you should not let the user know and log in secretly

letReqCount = 0 / / response blocker fly. The interceptors. Response. Use (async response = > {/ / / / agree with some response code statedoSthing // only returns the data field of the request result to console.log(response, response.request) // To check whether there is a response. If the token is invalid or has expired, enter the following methodif (response.data && response.data.code === '00000'ReqCount += 1 reqCount += 1 reqCount += 1 reqCount += 1if (reqCount < 3) {
        let data = await store.dispatch('wxLogin').then(async () => {// After successful login, reinitiate the previous request to get data, returnlet res = await fly.request(response.request).then(res => res)
            reqCount = 0
            return res
        })
    } else {
        mpvue.redirectTo({
          url: '/pages/login'})}return data
  } else {
    returnResponse.data}}, (err) => {wx.getNetworkType({success: res => {console.log(res))if (res.networkType === 'none') {
        wx.showToast({
          title: 'Current network is not available, please check your network Settings',
          icon: 'none',
          duration: 2000
        })
      } else {
        wx.showToast({
          title: 'Server busy, please try again later',
          icon: 'none', duration: 2000})}}}) console.log(err)}),Copy the code

Applets authorization judgment

Since mpvue is accessed from app. vue, I write authorization in app. vue

mountedGetSetting ({success: (res) => {// If there is no authorization, go to the login authorization page and ask him to authorizeif (res.authSetting['scope.userInfo'] === undefined) {
          if (this.$router.currentRoute && this.$router.currentRoute.path ! = ='/pages/login') {
            mpvue.navigateTo({
              url: '/pages/login'
            })
            return false}}else if (res.authSetting['scope.userInfo'] !== undefined && res.authSetting['scope.userInfo']! = =true) {
          console.log('Denial of Authorization')}else {
          // console.log('Authorized') // If the user is authorized to log in to this interface, the user can log in to this interface.$store.dispatch('wxLogin').then(() => {// Determine the page on which the current login action takes place. If it is the login authorization page, go to the home page; otherwise, stay on the current pageif (this.$router.currentRoute && this.$router.currentRoute.path === '/pages/login') {
              mpvue.switchTab({
                url: '/pages/index'
              })
            }
          })
        }
      },
      fail: res => {
        console.log(res)
      }
    })
  }
Copy the code