作者文章:https://segmentfault.com/a/1190000009506097

学习的框架:https://github.com/PanJiaChen/vue-element-admin

膜拜下大神

登陆页面 src/views/login/index.js

element-ui表单,验证:http://element.eleme.io/#/zh-CN/component/form
vuex:https://vuex.vuejs.org/zh-cn/modules.html

##是否展示密码

showPwd() { //展示密码
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
    }

##点击登陆按钮
this.$router.push() 路由跳转:https://router.vuejs.org/zh-cn/essentials/navigation.html

 handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) { //验证通过
          this.loading = true  //按钮加载中
          this.$store.dispatch('LoginByUsername', this.loginForm).then(() => {
            // store/user.js/LoginByUsername  //成功的情况
            this.loading = false
            this.$router.push({ path: '/' })
          }).catch(() => {
            this.loading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }

如果验证通过,那么就对用户名和密码进行检测
this.$store.dispatch: https://vuex.vuejs.org/zh-cn/actions.html (要学习action,mutations)
new Promise():https://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/0014345008539155e93fc16046d4bb7854943814c4f9dc2000

store/user.js/LoginByUsername

import { loginByUsername, logout, getUserInfo } from ‘@/api/login’
import { getToken, setToken, removeToken } from ‘@/utils/auth’

‘@/utils/auth’ //@指的是src

//通过Cookie.set设置
export function setToken(token) {
  return Cookies.set(TokenKey, token)
}
//请求数据
export function loginByUsername(username, password) {
    const data = {
        username,
        password
    }
    return request({ //向后台进行请求 类似于axios.post 详见下axios
            url: '/login/login',
            method: 'post',
            data
        })
        /**
         *  发送一个 POST 请求
          axios({
            method: 'post',
            url: '/user/12345',
            data: {
              firstName: 'Fred',
              lastName: 'Flintstone'
            }
          });
        */
}


  // 用户名登录
        LoginByUsername({ commit }, userInfo) {
            const username = userInfo.username.trim() //处理传递过来的数据
            //下面loginByUsername向后台发送username,userInfo.password获得登陆成功或失败的数据
            //成功则设置SET_TOKEN
            return new Promise((resolve, reject) => { //返回一个Promise对象
                loginByUsername(username, userInfo.password).then(response => {
                    const data = response.data
                    commit('SET_TOKEN', data.token)  //改变SET_TOKEN的值
                    setToken(data.token) // 通过 Cookies.set(TokenKey, token)
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },

上面的作用:登陆的时候 在vuex中保存用户信息token,在cookie中保存用户信息token(权限)

这里写图片描述

##axios
地址:https://www.kancloud.cn/yunye/axios/234845

import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
/*
export function getToken() {
  return Cookies.get(TokenKey)
}
*/

// create an axios instance
//https://www.cnblogs.com/zhouyangla/p/6753673.html
//创建一个axios实例
const service = axios.create({  //自定义实例默认值
    baseURL: process.env.BASE_API, // api的base_url
    timeout: 5000 // request timeout
})

// request interceptor 添加请求拦截器
service.interceptors.request.use(config => {
    // Do something before request is sent
    if (store.getters.token) {
        config.headers['X-Token'] = getToken() // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
    }
    return config
}, error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
})

// respone interceptor 添加响应拦截器
service.interceptors.response.use(
    response => response, //成功
    /**
     * 下面的注释为通过response自定义code来标示请求状态,当code返回如下情况为权限有问题,登出并返回到登录页
     * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
     */
    //  const res = response.data;
    //     if (res.code !== 20000) {
    //       Message({
    //         message: res.message,
    //         type: 'error',
    //         duration: 5 * 1000
    //       });
    //       // 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
    //       if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
    //         MessageBox.confirm('你已被登出,可以取消继续留在该页面,或者重新登录', '确定登出', {
    //           confirmButtonText: '重新登录',
    //           cancelButtonText: '取消',
    //           type: 'warning'
    //         }).then(() => {
    //           store.dispatch('FedLogOut').then(() => {
    //             location.reload();// 为了重新实例化vue-router对象 避免bug
    //           });
    //         })
    //       }
    //       return Promise.reject('error');
    //     } else {
    //       return response.data;
    //     }
    error => { //失败
        console.log('err' + error) // for debug
        Message({
            message: error.message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    })

export default service //导出 import request from '@/utils/request' 被命名为request

##中英文切换
学习:https://www.cnblogs.com/rogerwu/p/7744476.html
弹出框,确认框:http://element.eleme.io/#/zh-CN/component/message-box

 mutations: {
        TOGGLE_SIDEBAR: state => {
            if (state.sidebar.opened) {
                Cookies.set('sidebarStatus', 1)
            } else {
                Cookies.set('sidebarStatus', 0)
            }
            state.sidebar.opened = !state.sidebar.opened
        },
        SET_LANGUAGE: (state, language) => { //通过mutations来改变中英文状态
            state.language = language
            Cookies.set('language', language)
        }
    },
    actions: {
        toggleSideBar({ commit }) {
            commit('TOGGLE_SIDEBAR')
        },
        setLanguage({ commit }, language) {
            // 通过actions来改变中英文状态 (还是通过commit,调用mutations中的方法)
            // 只是在这个方法中可以异步来改变
            commit('SET_LANGUAGE', language)
        }
    }
export default {
  computed: {
    language() {
      return this.$store.getters.language; //得到的语言
      //getters是 state对象中的
    }
  },
  methods: {
    handleSetLanguage(lang) {
      // this.$i18n.locale = lang  //改变i18n语言种类
      // this.$store.dispatch('setLanguage', lang)
      // this.$message({
      //   message: 'switch language success',
      //   type: 'success'
      // }) 这是添加了一个确认按钮,也要在语言/lang/en.js/cn.js添上对应的语言
      this.$confirm(this.$t('confirm.tips'), this.$t('confirm.tips'), {
        confirmButtonText: this.$t('confirm.sure'),
        cancelButtonText: this.$t('confirm.no'),
        type: 'warning'
      })
        .then(() => {
          //  let locale = this.$i18n.locale
          //  locale === 'zh' ? this.$i18n.locale = 'en' : this.$i18n.locale = 'zh'
          this.$i18n.locale = lang; //改变i18n语言种类
          this.$store.dispatch('setLanguage', lang);//dispatch 来触发action中
          this.$message({
            message: 'switch language success',
            type: 'success'
          });
        })
        .catch(() => {
          this.$message({
              message: 'switch language fail',
            type: 'info'
          });
        });
    }
  }
};

###第三方登陆
el-dialog:http://element.eleme.io/#/zh-CN/component/dialog

import openWindow from '@/utils/openWindow'

export default {
  name: 'social-signin',
  methods: {
    wechatHandleClick(thirdpart) {
      this.$store.commit('SET_AUTH_TYPE', thirdpart) //作者未写此mutations
      const appid = 'xxxxx'
      const redirect_uri = encodeURIComponent('xxx/redirect?redirect=' + window.location.origin + '/authredirect')
      const url = 'https://open.weixin.qq.com/connect/qrconnect?appid=' + appid + '&redirect_uri=' + redirect_uri + '&response_type=code&scope=snsapi_login#wechat_redirect'
      openWindow(url, thirdpart, 540, 540)
    },
    tencentHandleClick(thirdpart) {
      this.$store.commit('SET_AUTH_TYPE', thirdpart)
      const client_id = 'xxxxx'
      const redirect_uri = encodeURIComponent('xxx/redirect?redirect=' + window.location.origin + '/authredirect')
      const url = 'https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=' + client_id + '&redirect_uri=' + redirect_uri
      openWindow(url, thirdpart, 540, 540) //打开一个浏览器窗口
    }
  }
}

例如点击微信图标


Logo

前往低代码交流专区

更多推荐