Home Web Front-end JS Tutorial Implement login and registration page permission interception by using vue+vuex+axios technologies (detailed tutorial)

Implement login and registration page permission interception by using vue+vuex+axios technologies (detailed tutorial)

May 31, 2018 pm 03:56 PM
several kinds technology

Now I will share with you an article about vue vuex axios to implement login and registration page permission interception. It has a good reference value and I hope it will be helpful to everyone.

There are many templates written on GitHub, and this project is also based on templates.

Now record the process I did

#1. Modify the BASE_API in dev.env.js in the config folder and change the address Change to the public part of the request backend

BASE_API: '"http://192.168.xx.xx"',
Copy after login

2. The next step is to operate the src file. First, write the vew component (login.vue,regist. vue), write it and configure the path in index.js in the router

login.vue

<template>
 <p class="login-container">
  <el-form autoComplete="on" :model="loginForm" :rules="loginRules" ref="loginForm" label-position="left"
     label-width="0px"
     class="card-box login-form">
   <h3 class="title">登录</h3>
   <el-form-item prop="name">
  <span class="svg-container svg-container_login">
   <svg-icon icon-class="user"/>
  </span>
    <el-input name="name" disabled type="text" v-model="loginForm.name" autoComplete="on"
      placeholder="用户名"/>
   </el-form-item>
   <el-form-item prop="password">
  <span class="svg-container">
   <svg-icon icon-class="password"></svg-icon>
  </span>
    <el-input name="password" :type="pwdType" @keyup.enter.native="handleLogin" v-model="loginForm.password"
      autoComplete="on"
      placeholder="密码"></el-input>
    <span class="show-pwd" @click="showPwd"><svg-icon icon-class="eye"/></span>
   </el-form-item>
   <el-form-item>
    <el-button type="primary" style="width:100%;" :loading="loading" @click.native.prevent="handleLogin">
    登录
    </el-button>
   </el-form-item>
  </el-form>
  </p>
</template>
<script>
 export default {
 name: &#39;login&#39;,
 data() {
  const validateUsername = (rule, value, callback) => {
  if (value.trim().length<1) {
   callback(new Error(&#39;用户名不能为空&#39;))
  } else {
   callback()
  }
  };
  const validatePass = (rule, value, callback) => {
  if (value.trim().length < 1) {
   callback(new Error(&#39;密码不能为空&#39;))
  } else {
   callback()
  }
  };
  return {
  loginForm: {
   name: &#39;&#39;,
   password: &#39;&#39;
  },
  loginRules: {
   name: [{required: true, trigger: &#39;blur&#39;, validator: validateUsername}],
   password: [{required: true, trigger: &#39;blur&#39;, validator: validatePass}]
  },
  loading: false,
  pwdType: &#39;password&#39;
  }
 },
 methods: {
  showPwd() {
  if (this.pwdType === &#39;password&#39;) {
   this.pwdType = &#39;&#39;
  } else {
   this.pwdType = &#39;password&#39;
  }
  },
  handleLogin() {
  this.$refs.loginForm.validate(valid => {
   if (valid) {
   this.loading = true;
   this.$store.dispatch(&#39;Login&#39;, this.loginForm).then(() => {
    this.loading = false;
    this.$router.push({path: &#39;/&#39;});
   }).catch((e) => {
    this.loading = false
   })
   } else {
   console.log(&#39;error submit!!&#39;)
   return false
   }
  })
  }
 }
 }
</script>
Copy after login

router/index.js

{ path: &#39;/login&#39;, component: _import(&#39;Login/login&#39;), hidden: true }
Copy after login

3. Write the interface address to connect with the backend in login.js in the api. Define user in user.js in modules in stores, including state, mutations, and action. The specific request operation is written in action. login.vue or register.vue calls the request written in user.js, getter.js Define store getters in

api/login.js

import request from &#39;@/utils/request&#39;
export function login(name,password) {
 return request({
 url: &#39;/XX/XX&#39;,
 method: &#39;post&#39;,
 data: {
  name,
  password
 } 
 })
}
Copy after login

##stores/modules/user. js

  import { login,regist,logout } from &#39;@/api/login&#39;
  import { getToken,setToken } from &#39;@/utils/auth&#39;
  const user = {
  state: {
   name:&#39;&#39;,
   token:&#39;&#39;
  },
  mutations: {
   SET_NAME: (state, name) => {
   state.name = name;
   },
   SET_TOKEN: (state, token) => {
   state.token = token;
   setToken(token);
   }
  },
  actions: {
   // 登录
   Login({ commit }, userInfo) {
   const name = userInfo.name.trim();
   const password = userInfo.password.trim();
   return new Promise((resolve, reject) => {
    login(name, password).then(response => {
    const data = response.data;
    commit(&#39;SET_NAME&#39;, data.name);
    commit(&#39;SET_TOKEN&#39;, data.token);
    setName(data.name);
    setToken(data.token);
    resolve(response); }).catch(error => { reject(error) }) }) },
   // 注册 
   Regist({ commit }, userInfo) { 
   const name= userInfo.name.trim(); 
   const password = userInfo.password.trim(); 
   return new Promise((resolve, reject) => { 
    regist(name, password).then(response => { 
    const data = response.data; 
    commit(&#39;SET_NAME&#39;, data.name); 
    commit(&#39;SET_TOKEN&#39;, data.token);
    setName(data.name);setToken(data.token); 
    resolve(response);
    }).catch(error => { 
    reject(error) }) }) }, 
   // 登出 
   LogOut({ commit, state }) {
   return new Promise((resolve, reject) => {
   logout().then(response => {
    commit(&#39;SET_NAME&#39;, &#39;&#39;);
    commit(&#39;SET_TOKEN&#39;, &#39;&#39;);
    setName(&#39;&#39;);
    setToken(false);
    //removeName();
    //removeToken();
    resolve(response);
   }).catch(error => {
    reject(error)
   })
   })
  }, 
   // 前端 登出 
   FedLogOut({ commit }) { 
   return new Promise(resolve => {
  setToken(false);
 commit(&#39;SET_TOKEN&#39;, false);
 resolve()
   })
   }
  }
  }
  export default user
Copy after login

getter.js:

const getters={
 name:state=>state.user.name,
 token:state=>state.user.token
}
export default getter
Copy after login

4. Operate cookies in auth.js in utils, write, read, delete user permissions, sign whether to log in, etc.

import Cookies from &#39;js-cookies&#39;
export function setName(name) {
 return Cookies.set("name", name);
}
export function getName() {
 return Cookies.get("name");
}
export function setToken(token) {
 return Cookies.set("token", token);
}
export function getToken() {
 return Cookies.get("token");
}
Copy after login

5. Write a whitelist in permission.js, intercept jumps outside the whitelist and jump to login. At the same time, determine user permissions, whether to log in, etc.

import router from &#39;./router&#39;
import store from &#39;./store&#39;
import NProgress from &#39;nprogress&#39; // Progress 进度条
import &#39;nprogress/nprogress.css&#39;// Progress 进度条样式
import {Message} from &#39;element-ui&#39;
import {getName, getToken} from "@/utils/auth"; // 验权
const whiteList = [&#39;/login&#39;, &#39;/regist&#39;]; // 不重定向白名单
router.beforeEach((to, from, next) => {
 NProgress.start();
 if (whiteList.indexOf(to.path) !== -1) {
 next();
 } else {
 if (getToken()==="true") {
  next();
  NProgress.done()
 } else {
  next({path: &#39;/login&#39;});
  NProgress.done()
 }
 }
})
router.afterEach(() => {
 NProgress.done() // 结束Progress
})
Copy after login

6. Write the interception code in request.js in utils, intercept the specific code returned by the backend and perform corresponding operations

import axios from &#39;axios&#39;
import { Message, MessageBox } from &#39;element-ui&#39;
import store from &#39;../store&#39;
// 创建axios实例
const service = axios.create({
 baseURL: process.env.BASE_API, // api的base_url
 timeout: 15000     // 请求超时时间
});
// respone拦截器
service.interceptors.response.use(
 response => {
 /**
 * code为非200是抛错 可结合自己业务进行修改
 */
 const res = response.data;
 //const res = response;
 if (res.code !== &#39;200&#39; && res.code !== 200) {
  if (res.code === &#39;4001&#39; || res.code === 4001) {
  MessageBox.confirm(&#39;用户名或密码错误,请重新登录&#39;, &#39;重新登录&#39;, {
   confirmButtonText: &#39;重新登录&#39;,
   cancelButtonText: &#39;取消&#39;,
   type: &#39;warning&#39;
  }).then(() => {
   store.dispatch(&#39;FedLogOut&#39;).then(() => {
    location.reload()// 为了重新实例化vue-router对象 避免bug
   })
  })
  }
  if (res.code === &#39;4009&#39; || res.code === 4009) {
  MessageBox.confirm(&#39;该用户名已存在,请重新注册!&#39;, &#39;重新注册&#39;, {
   confirmButtonText: &#39;重新注册&#39;,
   cancelButtonText: &#39;取消&#39;,
   type: &#39;warning&#39;
  }).then(() => {
   store.dispatch(&#39;FedLogOut&#39;).then(() => {
   location.reload()// 为了重新实例化vue-router对象 避免bug
   })
  })
  }
  return Promise.reject(&#39;error&#39;)
 } else {
  return response.data
 }
 },
 error => {
 Message({
  message: error.message,
  type: &#39;error&#39;,
  duration: 5 * 1000
 });
 return Promise.reject(error)
 }
)
export default service
Copy after login

above I compiled it for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Detailed explanation of red-black tree insertion and examples of Javascript implementation methods

js canvas implements sliding puzzle verification Code function

Summary of the method of converting JS from non-array object to array

The above is the detailed content of Implement login and registration page permission interception by using vue+vuex+axios technologies (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The Stable Diffusion 3 paper is finally released, and the architectural details are revealed. Will it help to reproduce Sora? The Stable Diffusion 3 paper is finally released, and the architectural details are revealed. Will it help to reproduce Sora? Mar 06, 2024 pm 05:34 PM

StableDiffusion3’s paper is finally here! This model was released two weeks ago and uses the same DiT (DiffusionTransformer) architecture as Sora. It caused quite a stir once it was released. Compared with the previous version, the quality of the images generated by StableDiffusion3 has been significantly improved. It now supports multi-theme prompts, and the text writing effect has also been improved, and garbled characters no longer appear. StabilityAI pointed out that StableDiffusion3 is a series of models with parameter sizes ranging from 800M to 8B. This parameter range means that the model can be run directly on many portable devices, significantly reducing the use of AI

Have you really mastered coordinate system conversion? Multi-sensor issues that are inseparable from autonomous driving Have you really mastered coordinate system conversion? Multi-sensor issues that are inseparable from autonomous driving Oct 12, 2023 am 11:21 AM

The first pilot and key article mainly introduces several commonly used coordinate systems in autonomous driving technology, and how to complete the correlation and conversion between them, and finally build a unified environment model. The focus here is to understand the conversion from vehicle to camera rigid body (external parameters), camera to image conversion (internal parameters), and image to pixel unit conversion. The conversion from 3D to 2D will have corresponding distortion, translation, etc. Key points: The vehicle coordinate system and the camera body coordinate system need to be rewritten: the plane coordinate system and the pixel coordinate system. Difficulty: image distortion must be considered. Both de-distortion and distortion addition are compensated on the image plane. 2. Introduction There are four vision systems in total. Coordinate system: pixel plane coordinate system (u, v), image coordinate system (x, y), camera coordinate system () and world coordinate system (). There is a relationship between each coordinate system,

This article is enough for you to read about autonomous driving and trajectory prediction! This article is enough for you to read about autonomous driving and trajectory prediction! Feb 28, 2024 pm 07:20 PM

Trajectory prediction plays an important role in autonomous driving. Autonomous driving trajectory prediction refers to predicting the future driving trajectory of the vehicle by analyzing various data during the vehicle's driving process. As the core module of autonomous driving, the quality of trajectory prediction is crucial to downstream planning control. The trajectory prediction task has a rich technology stack and requires familiarity with autonomous driving dynamic/static perception, high-precision maps, lane lines, neural network architecture (CNN&GNN&Transformer) skills, etc. It is very difficult to get started! Many fans hope to get started with trajectory prediction as soon as possible and avoid pitfalls. Today I will take stock of some common problems and introductory learning methods for trajectory prediction! Introductory related knowledge 1. Are the preview papers in order? A: Look at the survey first, p

DualBEV: significantly surpassing BEVFormer and BEVDet4D, open the book! DualBEV: significantly surpassing BEVFormer and BEVDet4D, open the book! Mar 21, 2024 pm 05:21 PM

This paper explores the problem of accurately detecting objects from different viewing angles (such as perspective and bird's-eye view) in autonomous driving, especially how to effectively transform features from perspective (PV) to bird's-eye view (BEV) space. Transformation is implemented via the Visual Transformation (VT) module. Existing methods are broadly divided into two strategies: 2D to 3D and 3D to 2D conversion. 2D-to-3D methods improve dense 2D features by predicting depth probabilities, but the inherent uncertainty of depth predictions, especially in distant regions, may introduce inaccuracies. While 3D to 2D methods usually use 3D queries to sample 2D features and learn the attention weights of the correspondence between 3D and 2D features through a Transformer, which increases the computational and deployment time.

The first multi-view autonomous driving scene video generation world model | DrivingDiffusion: New ideas for BEV data and simulation The first multi-view autonomous driving scene video generation world model | DrivingDiffusion: New ideas for BEV data and simulation Oct 23, 2023 am 11:13 AM

Some of the author’s personal thoughts In the field of autonomous driving, with the development of BEV-based sub-tasks/end-to-end solutions, high-quality multi-view training data and corresponding simulation scene construction have become increasingly important. In response to the pain points of current tasks, "high quality" can be decoupled into three aspects: long-tail scenarios in different dimensions: such as close-range vehicles in obstacle data and precise heading angles during car cutting, as well as lane line data. Scenes such as curves with different curvatures or ramps/mergings/mergings that are difficult to capture. These often rely on large amounts of data collection and complex data mining strategies, which are costly. 3D true value - highly consistent image: Current BEV data acquisition is often affected by errors in sensor installation/calibration, high-precision maps and the reconstruction algorithm itself. this led me to

GSLAM | A general SLAM architecture and benchmark GSLAM | A general SLAM architecture and benchmark Oct 20, 2023 am 11:37 AM

Suddenly discovered a 19-year-old paper GSLAM: A General SLAM Framework and Benchmark open source code: https://github.com/zdzhaoyong/GSLAM Go directly to the full text and feel the quality of this work ~ 1 Abstract SLAM technology has achieved many successes recently and attracted many attracted the attention of high-tech companies. However, how to effectively perform benchmarks on speed, robustness, and portability with interfaces to existing or emerging algorithms remains a problem. In this paper, a new SLAM platform called GSLAM is proposed, which not only provides evaluation capabilities but also provides researchers with a useful way to quickly develop their own SLAM systems.

'Minecraft' turns into an AI town, and NPC residents role-play like real people 'Minecraft' turns into an AI town, and NPC residents role-play like real people Jan 02, 2024 pm 06:25 PM

Please note that this square man is frowning, thinking about the identities of the "uninvited guests" in front of him. It turned out that she was in a dangerous situation, and once she realized this, she quickly began a mental search to find a strategy to solve the problem. Ultimately, she decided to flee the scene and then seek help as quickly as possible and take immediate action. At the same time, the person on the opposite side was thinking the same thing as her... There was such a scene in "Minecraft" where all the characters were controlled by artificial intelligence. Each of them has a unique identity setting. For example, the girl mentioned before is a 17-year-old but smart and brave courier. They have the ability to remember and think, and live like humans in this small town set in Minecraft. What drives them is a brand new,

Review! Deep model fusion (LLM/basic model/federated learning/fine-tuning, etc.) Review! Deep model fusion (LLM/basic model/federated learning/fine-tuning, etc.) Apr 18, 2024 pm 09:43 PM

In September 23, the paper "DeepModelFusion:ASurvey" was published by the National University of Defense Technology, JD.com and Beijing Institute of Technology. Deep model fusion/merging is an emerging technology that combines the parameters or predictions of multiple deep learning models into a single model. It combines the capabilities of different models to compensate for the biases and errors of individual models for better performance. Deep model fusion on large-scale deep learning models (such as LLM and basic models) faces some challenges, including high computational cost, high-dimensional parameter space, interference between different heterogeneous models, etc. This article divides existing deep model fusion methods into four categories: (1) "Pattern connection", which connects solutions in the weight space through a loss-reducing path to obtain a better initial model fusion

See all articles