Home Web Front-end JS Tutorial vue vuex vue-rouert permission routing (detailed tutorial)

vue vuex vue-rouert permission routing (detailed tutorial)

Jun 14, 2018 pm 03:29 PM
router vue vuex

This article mainly introduces the vue vuex vue-rouert background project - permission routing. Through this article, the relationship between vue vuex vue-router can be clearly understood. This version is very simple and suitable for beginners. Friends who need it can Refer to the project address of

: vue-simple-template

There are three roles in total: adan barbara carrie. The passwords are all: 123456

adan has the highest authority A and he can see red, yellow and blue pages (three pages in total)

barbara has permission B and he can see the red and yellow pages

carrie has permission C and he can see the red and blue pages

Technology stack

webpack ---- 打包神器
vue ---- JavaScript 框架
vuex ---- 实现不同组件间的状态共享
vue-router ---- 页面路由
babel-polyfill ---- 将ES6代码转为ES5代码
normalize.css ---- 重置掉该重置的样式
element-ui ---- UI组件库
Copy after login

Project initialization

# cd 到项目文件夹
cd weven-simple-template
# 安装依赖 (本项目还安装了其他依赖详情 请见 package.json 文件)
npm install
# 运行项目
npm run dev
Copy after login

Project structure

vue-cil After initializing the project with the scaffolding, I only modified the src folder

src
├── App.vue  ---- 页面入口
├── api  ---- api请求
│ └── login.js ---- 模拟json对象数据
├── assets  ---- 主题 字体等静态资源
│ └── logo.png
├── components ---- 组件
│ ├── index.vue
│ └── login.vue 
├── main.js  ---- 初始化组件 加载路由
├── router  ---- 路由
│ └── index.js
└── store  ---- vuex状态管理
 ├── getters.js
 ├── index.js
 └── modules
 └── login.js
Copy after login

Key points:

The key to dynamic routing is the coexistence of the meta field configured by the router and the status of vuex (if you don’t understand, you can check the official documentation first)

router/index .js

// 初始化路由
export default new Router({ 
 routes: [
 {
 path: '/login',
 name: 'Login',
 component: Login
 }
 ] 
});
// 动态路由 meta 定义了role
export const powerRouter =[ 
 { path: '/',redirect:'/red', name: 'index',component: Index,hidden:false,
 children: [
 { path: '/red', name: 'red', component: red,},
 { path: '/yellow', name: 'yellow', component: yellow, meta: {role: 'B'}},
 { path: '/blue', name: 'blue', component: blue, meta: {role: 'C'}}
 ]
 }
];
Copy after login

store/modules/lo

Logins({ commit }, info){
  return new Promise((resolve, reject) => {
  let data={};
  loginByUserInfo.map(function (item) { //获取所以用户信息
   if(info.username === item.username || info.pew === item.pew){
   commit('SET_USERNAME',item.username); //将username和role进行存储
   sessionStorage.setItem('USERNAME', item.username); //存入 session 
   commit('SET_ROLE',item.role);
   sessionStorage.setItem('ROLE', item.role);
   return data={username:item.username,introduce:item.introduce};
   }else{
   return data;
   }
  }); 
  resolve(data);
 }).catch(error => {
  reject(error);
 });
 },
 Roles({ commit }, newrouter){
 return new Promise((resolve, reject) => {
  commit('SET_NEWROUER',newrouter); //存储最新路由
  resolve(newrouter);
 }).catch(error => {
  reject(error);
 });
 },
Copy after login
Copy after login

gin.js actions part

Logins({ commit }, info){
  return new Promise((resolve, reject) => {
  let data={};
  loginByUserInfo.map(function (item) { //获取所以用户信息
   if(info.username === item.username || info.pew === item.pew){
   commit('SET_USERNAME',item.username); //将username和role进行存储
   sessionStorage.setItem('USERNAME', item.username); //存入 session 
   commit('SET_ROLE',item.role);
   sessionStorage.setItem('ROLE', item.role);
   return data={username:item.username,introduce:item.introduce};
   }else{
   return data;
   }
  }); 
  resolve(data);
 }).catch(error => {
  reject(error);
 });
 },
 Roles({ commit }, newrouter){
 return new Promise((resolve, reject) => {
  commit('SET_NEWROUER',newrouter); //存储最新路由
  resolve(newrouter);
 }).catch(error => {
  reject(error);
 });
 },
Copy after login
Copy after login

main.js

router.beforeEach((to, from, next) => {
 if(store.getters.role){ //判断role 是否存在
 
 if(store.getters.newrouter.length !== 0){ 
  next() //resolve 钩子
 }else{
  let newrouter
  if (store.getters.role == 'A') { //判断权限
  newrouter = powerRouter
  } else {
  let newchildren = powerRouter[0].children.filter(route => {
   if(route.meta){
   if(route.meta.role == store.getters.role){
    return true
   }
   return false
   }else{
   return true
   }
  });
  newrouter = powerRouter
  newrouter[0].children = newchildren
  }
  router.addRoutes(newrouter) //添加动态路由
  store.dispatch('Roles',newrouter).then(res => { 
  next({ ...to })
  }).catch(() => { 

  })
 } 
 }else{
  if (['/login'].indexOf(to.path) !== -1) { 
  next()
 } else {
  next('/login')
 }
 }
})
Copy after login

components/index.vue

// mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性
...mapGetters([
 'newrouter'
 ])
Copy after login

It is no problem to use this project to clarify the relationship between vue vuex vue-router. This can be said to be a super simple version, suitable for beginners. The key points mentioned in the above content are actually the whole project.

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

Related articles:

How to implement the function of uploading and compressing images in js (detailed tutorial)

How to calculate two using JS Time difference

How to introduce jquery in vue-cli webpack (detailed tutorial)

How to use files in vue

How to generate a drop-down list using pure js

The above is the detailed content of vue vuex vue-rouert permission routing (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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How to use Vue to implement electronic quotation forms with single header and multi-body? How to use Vue to implement electronic quotation forms with single header and multi-body? Apr 04, 2025 pm 11:39 PM

How to implement electronic quotation forms with single header and multi-body in Vue. In modern enterprise management, the electronic processing of quotation forms is to improve efficiency and...

How to implement the photo upload function of high-photographers of different brands on the front end? How to implement the photo upload function of high-photographers of different brands on the front end? Apr 04, 2025 pm 05:42 PM

How to implement the photo upload function of different brands of high-photographers on the front end When developing front-end projects, you often encounter the need to integrate hardware equipment. for...

Why is there no page request information on the console network after vue-router jump? Why is there no page request information on the console network after vue-router jump? Apr 04, 2025 pm 05:27 PM

Why is there no page request information on the console network after vue-router jump? When using vue-router for page redirection, you may notice a...

How to achieve segmentation effect with 45 degree curve border? How to achieve segmentation effect with 45 degree curve border? Apr 04, 2025 pm 11:48 PM

Tips for Implementing Segmenter Effects In user interface design, segmenter is a common navigation element, especially in mobile applications and responsive web pages. ...

How to use el-table to implement table grouping, drag and drop sorting in Vue2? How to use el-table to implement table grouping, drag and drop sorting in Vue2? Apr 04, 2025 pm 07:54 PM

Implementing el-table table group drag and drop sorting in Vue2. Using el-table tables to implement group drag and drop sorting in Vue2 is a common requirement. Suppose we have a...

Does JavaScript naming specification raise compatibility issues in Android WebView? Does JavaScript naming specification raise compatibility issues in Android WebView? Apr 04, 2025 pm 07:15 PM

JavaScript Naming Specification and Android...

How to make sure the bottom of a 3D object is fixed on the map using Mapbox and Three.js in Vue? How to make sure the bottom of a 3D object is fixed on the map using Mapbox and Three.js in Vue? Apr 04, 2025 pm 06:42 PM

How to use Mapbox and Three.js in Vue to adapt three-dimensional objects to map viewing angles. When using Vue to combine Mapbox and Three.js, the created three-dimensional objects need to...

See all articles