路由高阶用法 Vue2

1.几个注意点

Home.vue 

<template>
  <div>
    <h2>我是Home内容</h2>
    <ul class="nav nav-tabs">
      <li class="nav-item">
        <router-link class="nav-link" active-class="active" to="/home/news">News</router-link>
      </li>
      <li class="nav-item">
        <router-link class="nav-link" active-class="active" to="/home/message">Message</router-link>
      </li>
    </ul>

    <router-view></router-view>

  </div>
</template>

<script>
export default {
  name: "MyHome",
  // mounted() {
  //   console.log("MyHome组件挂载完毕了",this);
  // },
  //  beforeDestroy() {
  //     console.log("MyHome组件销毁了");

  //   },
};
</script>

<style>
</style>

 router.js

//该文件专门创建整个应用的路由器

import VueRouter from 'vue-router';
//引入组件
import MyAbout from '../pages/MyAbout.vue'
import MyHome from '../pages/MyHome.vue'

import MyNews from '../pages/MyNews.vue'
import MyMessage from '../pages/MyMessage.vue'
/**
 * 创建一个路由器
 */
const router = new VueRouter({
    routes: [
        {
            path: '/about',
            // component: MyAbout
            component: () => import('../pages/MyAbout.vue')
        },
        {
            //导入的两种方式
            path: '/home',
            // component: () => import('../pages/MyHome.vue')
            component: MyHome,
            children: [//二级路由 不加斜杠
                {
                    path: 'news',
                    component:MyNews
                },
                {
                    path: 'message',
                    component: MyMessage
                }
            ]
        }
    ]
})

export default router;

2.简化路由跳转 命名路由

命名重名了会优先找到前面先匹配的 也就是浅层次的 跳转

3.路由参数

 4.路由的props 的配置

5.路由replace属性 <route-link>

6.编程式路由导航

7.缓存路由组件

8.两个新的生命周期钩子 

剩下三个没有讲的钩子就在这了

 一个 nextTick 下一次模板渲染完毕时执行的回调

一个 activated 路由缓存切换到这个页面或者新建组件实例对象的时候

一个 deactivated 路由缓存切换走的时候 或者 组件销毁的时候

9.路由守卫

1.全局路由守卫 

route.js 

//该文件专门创建整个应用的路由器

import VueRouter from 'vue-router';
//引入组件
import MyAbout from '../pages/MyAbout.vue'
import MyHome from '../pages/MyHome.vue'

import MyNews from '../pages/MyNews.vue'
import MyMessage from '../pages/MyMessage.vue'
import MyDetail from '../pages/MyDetail.vue'
/**
 * 创建一个路由器
 */
const router = new VueRouter({
    routes: [
        {
            name: 'guanyu',
            path: '/about',
            // component: MyAbout
            component: () => import('../pages/MyAbout.vue'),
           meta:{
            title: '关于'
           }

        },
        {
            //导入的两种方式
            path: '/home',
            name: 'zhuye',
            // component: () => import('../pages/MyHome.vue')
            component: MyHome,
            meta:{
                title: '主页'
               },
            children: [//二级路由 不加斜杠
                {
                    
                    name: 'xinwen',
                    path: 'news',
                    component: MyNews,
                    meta:{
                        isAuth:true,
                          title: '新闻'
                    }
                },
                {
                    name: 'xiaoxi',
                    path: 'message',
                    component: MyMessage,
                    meta:{
                        isAuth:true,
                          title: '消息'
                    },
                    children: [
                        {
                            name: 'xiangqing',
                            // path: 'detail/:id/:title',
                            path: 'detail',
                            component: MyDetail,
                            meta:{
                                  title: '详情'
                            },
                            props($route) {
                                return {
                                    id: $route.query.id,
                                    title: $route.query.title
                                }
                            }
                        }
                    ]
                }
            ]
        }
    ]
})
//在每一次路由切换之前都会帮你调用一个函数

//全局前置路由守卫 初始化的时候被调用, 每次路由切换之前被调用
router.beforeEach((to,from,next)=>{
    console.log('路由全局前置守卫执行了');
    
    if(to.meta.isAuth){
        if(localStorage.getItem('school')==='shangguigu'){
            next()
        }else{
            alert('学校名不对暂无权限!')
        }
        
    }else{
        next()
    }
    
})

//全局前置路由守卫 初始化的时候被调用, 每次路由切换之后被调用
router.afterEach((to,from)=>{
    console.log('路由全局后置守卫执行了',to,from);
   const title = to.meta.title;
   if(title){
    document.title= title
   }else{
    document.title= '项目'
   }
    
})


export default router;

 2.独享路由守卫

3.组件内守卫

 route.js

//该文件专门创建整个应用的路由器

import VueRouter from 'vue-router';
//引入组件
import MyAbout from '../pages/MyAbout.vue'
import MyHome from '../pages/MyHome.vue'

import MyNews from '../pages/MyNews.vue'
import MyMessage from '../pages/MyMessage.vue'
import MyDetail from '../pages/MyDetail.vue'
/**
 * 创建一个路由器
 */
const router = new VueRouter({
    routes: [
        {
            name: 'guanyu',
            path: '/about',
            // component: MyAbout
            component: () => import('../pages/MyAbout.vue'),
            meta: {
                title: '关于'
            },
            //独享路由 只有前置没有后置
            beforeEnter(to, from, next) {
              console.log('独享路由前置守卫执行了');
              next()
            }

        },
        {
            //导入的两种方式
            path: '/home',
            name: 'zhuye',
            // component: () => import('../pages/MyHome.vue')
            component: MyHome,
            meta: {
                title: '主页'
            },
            children: [//二级路由 不加斜杠
                {

                    name: 'xinwen',
                    path: 'news',
                    component: MyNews,
                    meta: {
                        isAuth: true,
                        title: '新闻'
                    },
                    //独享路由 只有前置没有后置
                    beforeEnter(to, from, next) {
                        if (localStorage.getItem('school') === 'shangguigu') {
                            next()
                        } else {
                            alert('学校名不对暂无权限!')
                        }

                    }
                },
                {
                    name: 'xiaoxi',
                    path: 'message',
                    component: MyMessage,
                    meta: {
                        isAuth: true,
                        title: '消息'
                    },
                    children: [
                        {
                            name: 'xiangqing',
                            // path: 'detail/:id/:title',
                            path: 'detail',
                            component: MyDetail,
                            meta: {
                                title: '详情'
                            },
                            props($route) {
                                return {
                                    id: $route.query.id,
                                    title: $route.query.title
                                }
                            }
                        }
                    ]
                }
            ]
        }
    ]
})
//在每一次路由切换之前都会帮你调用一个函数

//全局前置路由守卫 初始化的时候被调用, 每次路由切换之前被调用
// router.beforeEach((to,from,next)=>{
//     console.log('路由全局前置守卫执行了');

//     if(to.meta.isAuth){
//         if(localStorage.getItem('school')==='shangguigu'){
//             next()
//         }else{
//             alert('学校名不对暂无权限!')
//         }

//     }else{
//         next()
//     }

// })

// //全局前置路由守卫 初始化的时候被调用, 每次路由切换之后被调用
router.afterEach((to, from) => {
    console.log('路由全局后置守卫执行了', to, from);
    const title = to.meta.title;
    if (title) {
        document.title = title
    } else {
        document.title = '项目'
    }

})


export default router;

myAbout.vue 

<template>
  <div>
    <h2>我是About内容</h2>
  </div>
</template>

<script>
export default {
  name:'MyAbout',
  // mounted() {
  //   console.log("MyAbout组件挂载完毕了");
  // },
  // beforeDestroy() {
  //   console.log("MyAbout组件销毁了");
    
  // },
//通过路由规则 进入该组件时被调用  组件内路由守卫
beforeRouteEnter(to,from,next){
  console.log("App--beforeRouteEnter",to,from,next);
  next()//放行
},
//通过路由规则 离开该组件时被调用
beforeRouteLeave(to,from,next){
   console.log("App--beforeRouteLeave",to,from,next);
   next()//放行
},

}
</script>

<style>

</style>

10.打包上线

1.执行打包 命令

npm run build

会在项目目录下生成一个dist文件夹

2.需要在服务器上面部署,才能够运行

在一个新的文件夹下输入  终端输入命令

npm init

然后输入打包的名字,然后一路回车 就是添基本信息, 这里我们可以不填,我们就一路回车

 3.安装 express

npm i express

右键 在工程目录下 新建一个文件夹 名为 server.js

const express = require('express'); //common模块化引入 相当于 ES6 import

const app = express();//就是一个函数,执行创建一个app实例对象

app.get('/person',(req,res)=>{
    res.send({
        name:'tom',
        age:18
    })
})

app.listen(5005,(err)=>{
    if(!err) return console.log('服务器启动成功!');

})

4.启动一个微型服务器

node server

加上一个静态资源配置

const express = require('express'); //common模块化引入 相当于 ES6 import

const app = express();//就是一个函数,执行创建一个app实例对象

app.use(express.static(__dirname+'/static'));//指定静态资源目录 __dirname:当前目录下


app.get('/person',(req,res)=>{
    res.send({
        name:'tom',
        age:18
    })
})

app.listen(5005,(err)=>{
    if(!err) return console.log('服务器启动成功!');

})

把dist目录下的东西拷贝到static文件夹下 ,重启服务器,就部署上去了

11.history模式问题

 这里要说明一个问题

history在 路径上面 的改变 重新刷新是会发送给服务器的 ,但是 服务器没有这个资源会 404 无法找到

但是hash就没有 这个问题 因为/#/ 后面跟的路径是不会被发往服务器的也就是会被当作Hash值。

1.HISTORY模式的解决办法

1.java解决

2.node.js有一个类库 专门解决这个问题

npm | Home (npmjs.com) 这个网站

connect-history-api-fallback 这个类库

下载类库

npm install  connect-history-api-fallback

服务器中间件

在服务器里面安装

const express = require('express'); //common模块化引入 相当于 ES6 import
const history = require('connect-history-api-fallback');


const app = express();//就是一个函数,执行创建一个app实例对象

app.use(history());//应用

app.use(express.static(__dirname+'/static'));//指定静态资源目录 __dirname:当前目录下


app.get('/person',(req,res)=>{
    res.send({
        name:'tom',
        age:18
    })
})

app.listen(5005,(err)=>{
    if(!err) return console.log('服务器启动成功!');

})

神奇般的解决了

  • 8
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值