vue-全局路由守卫和独立守卫的入门实例

实现效果:

当用户没有登录的信息时,不能访问其他的url,登录信息保存在Vuex的store.js中,登录信息持久保存。
实例:
当访问http://localhost:8080/#/时,直接调转到 http://localhost:8080/#/login,提交以后就能访问http://localhost:8080/#/
在这里插入图片描述

实现步骤

准备vuex —> Store

import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate' // 将state数据持久化,刷新以后数据也不会消失

Vue.use(Vuex)

/* eslint-disable no-new */
const store = new Vuex.Store({
  state: {
    login:"" //用来存储Login.vue中提交时用户信息
  },
  plugins: [createPersistedState()], // 使用createPersistedState组件
  modules: {},
  mutations:{
    //将提交的值赋值给state中的login
    loginModules(state,res){
      state.login=res;
    }
  }
})

export default store

第一步: 创建两个vue页面(准备两个页面做测试):HelloWorld.vue和Login.vue页面
HelloWold.vue

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <h2>Essential Links</h2>
    <ul>
      <li>
        <a href="https://vuejs.org" target="_blank"> Core Docs </a>
      </li>
      <li>
        <a href="https://forum.vuejs.org" target="_blank"> Forum </a>
      </li>
      <li>
        <a href="https://chat.vuejs.org" target="_blank"> Community Chat </a>
      </li>
      <li>
        <a href="https://twitter.com/vuejs" target="_blank"> Twitter </a>
      </li>
      <br />
      <li>
        <a href="http://vuejs-templates.github.io/webpack/" target="_blank">
          Docs for This Template
        </a>
      </li>
    </ul>
    <h2>Ecosystem</h2>
    <ul>
      <li>
        <a href="http://router.vuejs.org/" target="_blank"> vue-router </a>
      </li>
      <li>
        <a href="http://vuex.vuejs.org/" target="_blank"> vuex </a>
      </li>
      <li>
        <a href="http://vue-loader.vuejs.org/" target="_blank"> vue-loader </a>
      </li>
      <li>
        <a href="https://github.com/vuejs/awesome-vue" target="_blank">
          awesome-vue
        </a>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      msg: "Welcome to Your Vue.js App",
    };
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1,
h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

Login.vue

<template>
  <div>
    <h1>{{this.$store.state.login}}</h1>
    <input placeholder="输入...." v-model="username">
    <button @click="login()">提交</button>
    <button @click="loginOut()">取消</button>
  </div>
</template>
<script>

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    //这里存放数据
    return {
        username:""
    };
  },
  //方法集合
  methods: {
      login(){
          if(this.username != ""){
              this.$store.commit('loginModules',this.username);
              this.$router.push('/');
          }
      },
      loginOut(){
          this.$store.commit('loginModules',"");
          this.$router.push({path:'/hello'}); //自行编写一个退出后的vue页面,然后添加到router路由文件中。
      }
  }
};
</script>
<style>
</style>

第二步:管理router的文件 中添加两个路由:访问登录页;访问HelloWorld页面(不登录不能访问)

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Login from '@/components/Login'
Vue.use(Router)
export default new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld,
      meta:{
        // 用于判断是否需要进行登录信息的验证, true:访问 / ,需要有store->state的login有信息
        requireAuth: true
      }
    },
    {
      path:'/login',
      name:'Login',
      component: Login
    }
  ]
})

第三步: main.js中设置全局守卫

import store from './store/index'

router.beforeEach((to,from,next)=>{
  if(to.meta.requireAuth){
    console.log(store.state.login);
    if(store.state.login){
      next()
    }else{
      next({name:'Login'})
      //next({path:'/login'})
    }
  }else{
    next()
  }
});

思路:【
	如果(即将进入的这个路由需要权限才能进入){
	
		如果(能获取到这个老哥的userID){
			就让这个老哥进入这个路由
		}否则{
			就让这个老哥进入b这个页面
		}
		
	} 即将进入的路由不需要权限就能进入 {
	
		就让这个老哥进入这个路由
		
	}
】
思路参考链接:https://blog.youkuaiyun.com/heshuaicsdn/article/details/88020796

单独路由守卫-- beforeEnter

只需要在router中使用beforeEnter即可

    {
        path: '/foo',
        component: Foo,
        beforeEnter: (to, from, next) => {
        //编写一些判断的业务逻辑,比如store中有没有保存一些信息,有的跳转那个页面,没有跳转到那个页面
            console.log(to, from);
            next();
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值