Vuex implements different permissions for logged in and non-logged in
This time I will bring you vuex to implement different permissions for login and non-login, and vuex to implement different permissions for login and non-login. What are the precautions. Here is a practical case. Let’s take a look. .
The basic idea is to use vuex state management to store the login status (actually, it means to store a value, such as token), and then judge the login status before routing jump. You can use vue-router's global front guard beforeEach, or you can use routing Exclusive guard beforeEnter.
Navigation Guard
As the name suggests, the navigation guards provided by vue-router are mainly used to guard navigation by jumping or canceling. There are many opportunities to be embedded in the route navigation process: global, Exclusive to a single route, or component-level. Remember that changes to parameters or queries do not trigger enter/leave navigation guards. You can do this by observing $route Object to handle these changes, or use a beforeRouteUpdate guard within the component.
Complete navigation analysis process
1. Navigation is triggered.
2. Call the leave guard in the deactivated component.
3. Call the global beforeEach guard.
4. Call the beforeRouteUpdate guard (2.2) in the reused component.
5. Call beforeEnter in the routing configuration.
6. Parse asynchronous routing components.
7. Call beforeRouteEnter in the activated component.
8. Call the global beforeResolve guard (2.5).
9. Navigation is confirmed.
10. Call the global afterEach hook.
11. Trigger DOM update.
12. Use the created instance to call the callback function passed to next in the beforeRouteEnter guard.
Global Guard
You can use router.beforeEach to register a global front guard
const router = new VueRouter({ ... }) router.beforeEach((to, from, next) => { // ... })
When a navigation is triggered, global front guards are called in the order they were created. Guards are parsed and executed asynchronously. At this time, the navigation is waiting until all guards are resolved.
Each guard method receives three parameters:
to: Route: The target routing object that is about to enter
from: Route: The route that the current navigation is leaving
next: Function: This method must be called to resolve this hook. The execution effect depends on the calling parameters of the next method.
next(): Proceed to the next hook in the pipeline. If all hooks are executed, the navigation status is confirmed.
next(false): Interrupt current navigation. If the browser's URL changes (perhaps manually by the user or by the browser's back button), the URL address will be reset to the address corresponding to the from route.
next('/') or next({ path: '/' }): Jump to a different address. The current navigation is interrupted and a new navigation is started.
next(error):(2.4.0) If the parameter passed to next is an Error instance, the navigation will be terminated and the error will be passed to the callback registered by router.onError().
Make sure to call the next method, otherwise the hook will not be resolved.
Route exclusive guard
You can define the beforeEnter guard directly on the routing configuration:
const router = new VueRouter({ routes: [ { path: '/foo', component: Foo, beforeEnter: (to, from, next) => { // ... } } ] })
There are other guards. For details, please see the official documentationhttps://router.vuejs.org/zh-cn/advanced/navigation-guards.html
After installing vuex
Create store.js
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex); const state = { isLogin: 0 } const mutations = { changeLogin(state,status){ state.isLogin = status; } } const actions = { loginAction({commit}){ commit('changeLogin',1); } } export default new Vuex.Store({ state, actions, mutations })
login.vue中
Introduce import { mapActions,mapState } from 'vuex'
Then change the login status, base_url is the path
export default { name: 'Login', data(){ return{ loginForm: { username: '', password: '', }, rules: { username: [ { required: true, message: '请输入用户名', trigger: 'blur' }, ], password: [ { required: true, message: '请输入密码', trigger: 'blur' } ], }, showLogin: false } }, mounted(){ this.showLogin = true; }, computed: { ...mapState(['isLogin']) }, methods: { ...mapActions(['loginAction']), submitForm(formName){ this.$refs[formName].validate((valid) => { if(valid){ if(this.loginForm.username == 'aaa' && this.loginForm.password == '111'){ console.log('验证通过'); this.loginAction(); this.$router.push('manage'); }else{ console.log('账号密码出错'); // this.$message.error('账号密码出错'); this.$message({ type: 'error', message: '账号密码出错' }); } console.log('请求地址: ' + base_url); }else{ console.log('验证失败'); return false; } }) } } }
Next, just use the routing guard
beforeEach usage example
router.beforeEach((to,from,next)=>{ if(to.meta.check){ var check = async function(){ const result = await checkUser(); if(result.status == 0){ next(); }else{ alert('用户未登录'); next({path: '/login'}); } } check(); //后台验证session }else{ next(); } })
beforeEnter usage example
export default new Router({ routes: [ { path: '/login', component: Login }, { path: '/manage', name: '', component: Manage, beforeEnter: (to,from,next)=> { //导航守卫 console.log(to) console.log(from) if(store.state.isLogin == 1){ console.log('用户已经登录'); next(); }else{ console.log('用户未登录'); next({path: '/login',query:{ Rurl: to.fullPath}}); //未登录则跳转到登陆界面,query:{ Rurl: to.fullPath}表示把当前路由信息传递过去方便登录后跳转回来 } } } ] })
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of Vuex implements different permissions for logged in and non-logged in. For more information, please follow other related articles on the PHP Chinese website!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1
Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
