Vue路由的使用和导航守卫

Vue路由的使用和导航守卫

我们在使用vue-router的时候一般都是使用<script src = "xxx"来引入并且直接在一个界面中写所有的路由,但是如果是在实际开发中的话并不会这样编写,而是会以Vue-CLI来创建并且使用,所以我们的引用方式就会大不相同(在此代码我我都会给出注释,但是安装的步骤就不详细编写)

  1. 1、全局安装 vue-cli( -g是全局的全称 “-global”)
  2. npm install -g vue-cli
  3. 2、创建基于一个webpack版块的项目
  4. vue init webpack vue-cli
  5. 2、1安装依赖
  6. cd vue-cli##找到项目名
  7. npm install ##安装依赖
  8. npm run dev ##启动项目

**

一、在VUE-CLI中使用VUE路由器

最终实现效果:点击各自链接进入相应界面

实现步骤:
1、首先确认安装了VUE路由器
可以在 VUE-CLI中看packjson.json里看有无依赖

  1. “vue-router”: “^3.0.6”

2、同样也确保VUE-CLI根SRC目录下的main下引入了路由器

//main.js
 1. import Vue from 'vue' 
 2. import App from './App' 
 3. //引入的路由
 4. import { routes } from  './routes'
 5. 
 6. Vue.config.productionTip = false
 6.
 new Vue({
 el: '#app',
 //声明了路由
  router,
  components: { App },
  template: '<App/>'
})

3、由于在main.js里面引入了路由器import { routes } from ‘./routes’ 因此我们要保证index.js里面的代码正确并且正确

//index.js
import Vue from 'vue'
import Router from 'vue-router'
//以下两个界面自己创建
import HelloWorld from '@/components/HelloWorld'
import Admin from '@/components/Admin'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    },
    {
      path: '/admin',
      name: 'Admin',
      component: Admin
    }
  ]
})

4、由于在index.js里引入了src目录下的HelloWorld.vue 因此可能需要完善代码
所以以下是我们引入界面的代码:

HelloWorld.vue界面代码
	<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <h2>Essential Links</h2>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
        msg: 'Welcome to Your Vue.js App' //是在点击完毕之后要显示到<router-view>里的
    }
  }
}
</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>

6、以下是另一个跳转界面Admin.vue的代码,这是界面的代码

Admin.vue
<template>
    <div>
      <h1>管理员</h1>
    </div>
</template>

<script>
    export default {

    }
</script>

<style scoped>

</style>

7、修改SRC根目录下的App.vue其中的内容

App.vue
<template>
  <div id="app">
    
    <h1>我是src/app.vue的h1</h1>
    <router-link to="/">点击进入helloWorld首页</router-link>
    <br>
    <router-link to="/admin">点击进入Admin管理界面</router-link>
    <br>
    <router-view></router-view>
  </div>
</template>
 
 
 
<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

通过以上几个步骤,大概就已经实现了路由的跳转

二.实现路由导航守卫

如何设置一个全局守卫

你可以使用 router.beforeEach 注册一个全局前置守卫:就是在你router配置的下方注册

扫描二维码关注公众号,回复: 11331013 查看本文章
const router = new VueRouter({ ... })

router.beforeEach((to, from, next) => {
  // ...
})

当一个导航触发时,全局前置守卫按照创建顺序调用。守卫是异步解析执行,此时导航在所有守卫 resolve 完之前一直处于 等待中。

每个守卫方法接收三个参数:

to: Route: 即将要进入的目标 路由对象

from: Route: 当前导航正要离开的路由

next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。

一个简单的小例子

import Vue from 'vue';
import Router from 'vue-router';
import LoginPage from '@/pages/login';
import HomePage from '@/pages/home';
import GoodsListPage from '@/pages/good-list';
import GoodsDetailPage from '@/pages/good-detail';
import CartPage from '@/pages/cart';
import ProfilePage from '@/pages/profile';

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/',  // 默认进入路由
      redirect: '/home'   //重定向
    },
    {
      path: '/login',
      name: 'login',
      component: LoginPage
    },
    {
      path: '/home',
      name: 'home',
      component: HomePage
    },
    {
      path: '/good-list',
      name: 'good-list',
      component: GoodsListPage
    },
    {
      path: '/good-detail',
      name: 'good-detail',
      component: GoodsDetailPage
    },
    {
      path: '/cart',
      name: 'cart',
      component: CartPage
    },
    {
      path: '/profile',
      name: 'profile',
      component: ProfilePage
    },
    {
      path: '**',   // 错误路由
      redirect: '/home'   //重定向
    },
  ]
});

// 全局路由守卫
router.beforeEach((to, from, next) => {
  console.log('navigation-guards');
  // to: Route: 即将要进入的目标 路由对象
  // from: Route: 当前导航正要离开的路由
  // next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。

  const nextRoute = ['home', 'good-list', 'good-detail', 'cart', 'profile'];
  let isLogin = global.isLogin;  // 是否登录
  // 未登录状态;当路由到nextRoute指定页时,跳转至login
  if (nextRoute.indexOf(to.name) >= 0) {  
    if (!isLogin) {
      console.log('what fuck');
      router.push({ name: 'login' })
    }
  }
  // 已登录状态;当路由到login时,跳转至home 
  if (to.name === 'login') {
    if (isLogin) {
      router.push({ name: 'home' });
    }
  }
  next();
});

export default router;

VUE路由器官网路由:https : //router.vuejs.org/zh/guide/

vuex的官网地址:https ://vuex.vuejs.org/zh/getting-started.html

vuex的教程地址:http ://jspang.com/2017/05/03/vuex/

猜你喜欢

转载自blog.csdn.net/qq_43301471/article/details/90739708