Home Web Front-end JS Tutorial Detailed explanation of vue vuex vue-rouert permission routing example

Detailed explanation of vue vuex vue-rouert permission routing example

Dec 29, 2017 pm 04:51 PM
vuex Example

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 For reference, I hope it can help everyone.

Project address: vue-simple-template

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

adan has the highest authority A. 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 the scaffolding initializes the project, 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 point:

The key to dynamic routing lies in the router configuration The meta field and the status of vuex coexist (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 section


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 super Simple version, suitable for beginners. The key points mentioned in the above content are actually the whole project.

Project address: vue-simple-template

Related recommendations:

Detailed explanation Vue routing nested SPA implementation steps

Instance detailed explanation of vue mounting routing to the head navigation

Detailed explanation of route verification and corresponding interception in vue Instructions

The above is the detailed content of Detailed explanation of vue vuex vue-rouert permission routing example. 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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 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)

SVM examples in Python SVM examples in Python Jun 11, 2023 pm 08:42 PM

Support Vector Machine (SVM) in Python is a powerful supervised learning algorithm that can be used to solve classification and regression problems. SVM performs well when dealing with high-dimensional data and non-linear problems, and is widely used in data mining, image classification, text classification, bioinformatics and other fields. In this article, we will introduce an example of using SVM for classification in Python. We will use the SVM model from the scikit-learn library

Best practices for using Vuex to manage global state in Vue2.x Best practices for using Vuex to manage global state in Vue2.x Jun 09, 2023 pm 04:07 PM

Vue2.x is one of the most popular front-end frameworks currently, which provides Vuex as a solution for managing global state. Using Vuex can make state management clearer and easier to maintain. The best practices of Vuex will be introduced below to help developers better use Vuex and improve code quality. 1. Use modular organization state. Vuex uses a single state tree to manage all the states of the application, extracting the state from the components, making state management clearer and easier to understand. In applications with a lot of state, modules must be used

How to solve the problem 'Error: [vuex] do not mutate vuex store state outside mutation handlers.' when using vuex in a Vue application? How to solve the problem 'Error: [vuex] do not mutate vuex store state outside mutation handlers.' when using vuex in a Vue application? Jun 24, 2023 pm 07:04 PM

In Vue applications, using vuex is a common state management method. However, when using vuex, we may sometimes encounter such an error message: "Error:[vuex]donotmutatevuexstorestateoutsidemutationhandlers." What does this error message mean? Why does this error message appear? How to fix this error? This article will cover this issue in detail. The error message contains

How to use Vuex in Vue3 How to use Vuex in Vue3 May 14, 2023 pm 08:28 PM

What does Vuex do? Vue official: State management tool What is state management? State that needs to be shared among multiple components, and it is responsive, one change, all changes. For example, some globally used status information: user login status, user name, geographical location information, items in the shopping cart, etc. At this time, we need such a tool for global status management, and Vuex is such a tool. Single-page state management View–>Actions—>State view layer (view) triggers an action (action) to change the state (state) and responds back to the view layer (view) vuex (Vue3.

VUE3 Getting Started Example: Making a Simple Video Player VUE3 Getting Started Example: Making a Simple Video Player Jun 15, 2023 pm 09:42 PM

As the new generation of front-end frameworks continues to emerge, VUE3 is loved as a fast, flexible, and easy-to-use front-end framework. Next, let's learn the basics of VUE3 and make a simple video player. 1. Install VUE3 First, we need to install VUE3 locally. Open the command line tool and execute the following command: npminstallvue@next Then, create a new HTML file and introduce VUE3: <!doctypehtml>

How to solve the problem 'Error: [vuex] unknown action type: xxx' when using vuex in a Vue application? How to solve the problem 'Error: [vuex] unknown action type: xxx' when using vuex in a Vue application? Jun 25, 2023 pm 12:09 PM

In Vue.js projects, vuex is a very useful state management tool. It helps us share state among multiple components and provides a reliable way to manage state changes. But when using vuex, sometimes you will encounter the error "Error:[vuex]unknownactiontype:xxx". This article will explain the cause and solution of this error. 1. Cause of the error When using vuex, we need to define some actions and mu

Learn more about the implementation principles of vuex Learn more about the implementation principles of vuex Mar 20, 2023 pm 06:14 PM

When asked in an interview about the implementation principle of vuex, how should you answer? The following article will give you an in-depth understanding of the implementation principle of vuex. I hope it will be helpful to you!

Learn best practice examples of pointer conversion in Golang Learn best practice examples of pointer conversion in Golang Feb 24, 2024 pm 03:51 PM

Golang is a powerful and efficient programming language that can be used to develop various applications and services. In Golang, pointers are a very important concept, which can help us operate data more flexibly and efficiently. Pointer conversion refers to the process of pointer operations between different types. This article will use specific examples to learn the best practices of pointer conversion in Golang. 1. Basic concepts In Golang, each variable has an address, and the address is the location of the variable in memory.

See all articles