02.vue-router的进阶使用

关键字:路由懒加载,全局导航守卫,组件导航守卫,redirect重定向,keep-alive,params,query


一、目录结构

          

二、index.js 

  1 // 配置路由相关的信息
  2 import VueRouter from 'vue-router'
  3 import Vue from 'vue'
  4 
  5 // 一般加载方法
  6 // import Home from '../components/Home'
  7 // import About from '../components/About'
  8 // import User from '../components/User'
  9 
 10 // 路由懒加载方法(ES6)
 11 const Home = () => import('../components/Home');
 12 const HomeNews = () => import("../components/HomeNews");
 13 const HomeMessage = () => import("../components/HomeMessage");
 14 
 15 const About = () => import("../components/About");
 16 const User = () => import('../components/User');
 17 const Profile = () => import('../components/Profile');
 18 
 19 // 1.通过Vue.use(插件), 安装插件
 20 Vue.use(VueRouter);
 21 
 22 // 2.创建VueRouter对象
 23 const routes = [
 24   {
 25     path: '',
 26     // redirect重定向(到默认页面)
 27     // redirect: '/home'
 28     redirect: '/home',
 29     meta:{
 30       title: '首页'
 31     }
 32   },
 33   {
 34     path: '/home',
 35     component: Home,
 36     meta : {
 37       title: '首页'
 38     },
 39     children: [
 40       {
 41         path: '',
 42         redirect: "news",
 43       },
 44       {
 45         path: 'news',
 46         component: HomeNews,
 47       },
 48       {
 49         path: "message",
 50         component: HomeMessage,
 51       },
 52     ]
 53   },
 54   {
 55     path: '/about',
 56     component: About,
 57     meta: {
 58       title: "关于"
 59     }
 60   },
 61   {
 62     path: '/user/:userId',
 63     component: User,
 64     meta:{
 65       title: '用户'
 66 
 67     }
 68   },
 69   {
 70     path: '/profile',
 71     component: Profile,
 72     meta: {
 73       title: '档案'
 74     }
 75   }
 76 ];
 77 const router = new VueRouter({
 78   // 配置路由和组件之间的应用关系
 79   routes,
 80   // mode: 'history',默认是hash
 81   mode: 'history',
 82   // linkActiveClass: 'active' 
 83   // 统一简化class-active成active
 84   linkActiveClass: "active"
 85 });
 86 
 87 // guard (守卫,警卫)
 88 // 全局导航守卫,传一个函数
 89 // 前置守卫(也叫前置钩子hook)
 90 router.beforeEach((to,from,next) => {
 91   // 从from路由跳到to路由
 92   // to就是meta的对象
 93   document.title = to.matched[0].meta.title;
 94   console.log("前置导航守卫");
 95   // 原先会自动执行next(),但我们现在重新创建了beforeEach,所以必须手动执行下next(),
 96   next()
 97 });
 98 
 99 // 全局后置钩子
100 router.afterEach(()=>{
101   console.log("后置导航守卫");
102 });
103 
104 // 3.将router对象传入到Vue实例
105 export default router
View Code

三、main.js

 1 import Vue from 'vue'
 2 import App from './App'
 3 import router from './router'
 4 
 5 Vue.config.productionTip = false;
 6 
 7 // 全局Vue类下定义一个实例,可全局访问
 8 Vue.prototype.Test001 = function () {
 9   console.log("Test001")
10 };
11 Vue.prototype.Name001 = "zwnsyw";
12 
13 new Vue({
14   el: '#app',
15   router,
16   render: h => h(App)
17 })
View Code

四、App.vue

 1 <template>
 2   <div id="app">
 3     <h2>我是APP组件</h2>
 4     <!-- tag(定义渲染成什么标签)、replace(浏览器返回按钮不可用) 、active-class(活跃时添加class类active)-->
 5     <!--<router-link to="/home" tag="button" replace active-class="active">首页</router-link>-->
 6     <!--<router-link to="/about" tag="button" replace active-class="active">关于</router-link>-->
 7     <!--<router-link to="/home" tag="button" replace>首页</router-link>-->
 8     <!--<router-link to="/about" tag="button" replace>关于</router-link>-->
 9 <!--    <button @click="homeClick">首页</button>-->
10 <!--    <button @click="aboutClick">关于</button>-->
11     <router-link to="/home" tag="button" replace>首页</router-link>
12     <router-link to="/about" tag="button" replace>关于</router-link>
13     <router-link v-bind:to="'/user/'+userId">用户</router-link>
14 <!--    <router-link :to="{path: '/profile',query:{name: 'zwnsyw', age: 18, height: 1.88}}">档案</router-link>-->
15     <button @click="profileClick">档案</button>
16 
17 <!--    保持活跃状态,不要每次都重新创建-->
18 <!--    excloud是排除某些控件,让这些控件频繁的创建和销毁,两个之间不可加空格-->
19     <keep-alive exclude="Profile,User">
20       <router-view></router-view>
21     </keep-alive>
22 
23   </div>
24 </template>
25 
26 <script>
27 export default {
28   name: 'App',
29   data(){
30     return {
31       userId: "lisi",
32       img: 'http'
33     }
34   },
35   methods: {
36     homeClick() {
37       // 通过代码的方式修改路由 vue-router
38       // push => pushState
39       // this.$router.push('/home')
40       this.$router.replace('/home')
41       console.log('homeClick');
42     },
43     aboutClick() {
44       // this.$router.push('/about')
45       this.$router.replace('/about')
46       // this.$router.push('/about')
47       console.log('aboutClick');
48     },
49     profileClick(){
50       this.$router.push({
51         path: '/profile',
52         query: {
53           name: 'kobe',
54           age: '45',
55           height: '1.98'
56         }
57       })
58     }
59   }
60 }
61 </script>
62 
63 <style>
64   /*.router-link-active {*/
65     /*color: #f00;*/
66   /*}*/
67 
68   .active {
69     color: #f00;
70   }
71 </style>
View Code

五、Home.vue

 1 <template>
 2   <div>
 3     <h2>我是首页</h2>
 4     <p>我是首页内容, 哈哈哈</p>
 5     <router-link to="/home/news">新闻</router-link>
 6     <router-link to="/home/message">消息</router-link>
 7     <router-view></router-view>
 8   </div>
 9 </template>
10 
11 <script>
12   export default {
13     name: "Home",
14     data(){
15       return{
16         path: "/home/news"
17       }
18     },
19     // 这两个函数,只有该组件被保持了状态,使用了keep-alive时,才是有效的
20     // 组件活跃的时候回调
21     activated() {
22       this.$router.push(this.path);
23       console.log("activated");
24     },
25 
26     // 组件不活跃,销毁的时候回调
27     deactivated(){
28       console.log("deactivated");
29     },
30     // 组件导航守卫
31     beforeRouteLeave(to , from, next){
32       this.path = this.$route.path;
33       next()
34     },
35   }
36 
37 </script>
38 
39 <style scoped>
40 
41 </style>
View Code
 1 <template>
 2   <div>
 3     <ul>
 4       <li>消息1</li>
 5       <li>消息2</li>
 6       <li>消息3</li>
 7       <li>消息4</li>
 8     </ul>
 9   </div>
10 </template>
11 
12 <script>
13   export default {
14     name: "HomeMessage"
15   }
16 </script>
17 
18 <style scoped>
19 
20 </style>
HomeMessage
 1 <template>
 2   <div>
 3 <!--    ul>li{新闻$}*4-->
 4     <ul>
 5       <li>新闻1</li>
 6       <li>新闻2</li>
 7       <li>新闻3</li>
 8       <li>新闻4</li>
 9     </ul>
10     <button @click="btn_test">访问自定义全局实例</button>
11   </div>
12 </template>
13 
14 <script>
15   export default {
16     name: "Homenews",
17     methods:{
18       btn_test(){
19         console.log(this.Test001());
20         console.log(this.Name001)
21       }
22     }
23   }
24 </script>
25 
26 <style scoped>
27 
28 </style>
Homenews

六、About.vue

 1 <template>
 2   <div>
 3     <h2>我是关于</h2>
 4     <p>我是关于内容, 呵呵呵</p>
 5   </div>
 6 </template>
 7 
 8 <script>
 9   export default {
10     name: "About"
11   }
12 </script>
13 
14 <style scoped>
15 
16 </style>
View Code

七、User.vue

 1 <template>
 2   <div>
 3     <h2>我是用户</h2>
 4     <p>我是用户内容,嘿嘿嘿</p>
 5     <h2>{{userId}}</h2>
 6     <h2>{{$route.params.userId}}</h2>
 7   </div>
 8 </template>
 9 
10 <script>
11   export default {
12     name: "User",
13     computed:{
14       userId(){
15 
16         // 所有的组件都继承于Vue类的原型
17 
18         // route 拿到的是当前活跃的路由对象
19         // router 拿到的是index.js里面new出来的总路由对象
20         return this.$route.params.userId  // parameters(参数)
21       }
22     }
23   }
24 </script>
25 
26 <style scoped>
27 
28 </style>
View Code

八、Profile.vue

 1 <template>
 2 <div>
 3   <h2>我是Profile组件</h2>
 4   <h2>{{$route.query}}</h2>
 5   <h2>{{$route.query.name}}</h2>
 6   <h2>{{$route.query.age}}</h2>
 7   <h2>{{$route.query.height}}</h2>
 8 </div>
 9 </template>
10 
11 <script>
12   export default {
13     name: "Profile"
14   }
15 </script>
16 
17 <style scoped>
18 
19 </style>
View Code
原文地址:https://www.cnblogs.com/zwnsyw/p/12312744.html