Vue 2学习(路由、history 和 hash 模式、)-day014

一、路由简介

  1. 路由(route)就是一组 key-value 的对应关系
  2. 多个路由,需要经过路由器(router)的管理

在 Vue 中也有路由,Vue 中的路由主要是通过 vue-rounter 这个插件库来实现,它的作用就是专门用来实现 SPA 应用的

对 SPA 应用的理解:

  1. 单页 Web 应用(single page web application,SPA)
  2. 整个应用只有一个完整的页面
  3. 点击页面中的导航链接不会刷新页面,只会做页面的局部更新
  4. 数据需要通过 Ajax 请求获取

 二、路由的基本使用

注意事项

  • 路由组件通常存放在 pages 文件夹,一般组件通常存放在 components 文件夹
  • 通过切换,"隐藏"了路由组件,默认是被销毁的,需要的时候再去挂载
  • 每个组件都有自己的 $route 属性,里面存储着自己的路由信息
  • 整个应用只有一个 router 路由器,可以通过组件的 $router 属性获取到
     

 1- 安装 并引入 vue-router

  • Vue 2:安装 vue-router 3
  • Vue 3:安装 vue-router 4

我们现在学习所用的 Vue 的版本是 2 版本,所以我们需要使用如下命令安装 vue-router 3

          npm install vue-router@3

 在 /src/router/index.js 中创建整个应用的路由器

// 该文件专门用于创建整个路由器
import VueRouter from 'vue-router'

// 引入组件
import About from '../pages/About'
import Home from '../pages/Home'

// 创建并暴露一个路由器
export default new VueRouter({
    routes:[
        {
            path:'/about',
            component:About
        },
        {
            path:'/home',
            component:Home
        }
    ]
})

在 src/main.js 中引入和使用该插件  vue-router   ,步骤 1和 1-1

在 src/main.js 中引入路由器,并添加暴露出来,步骤 2 和 3

import Vue from 'vue'
import App from './App.vue'

// 1- 引入 vue-router
import VueRouter from 'vue-router'
// 2-引入路由器
import router from './router'

// 1-1应用 vue-router
Vue.use(VueRouter)

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
  // 3-在 vm 中添加路由器
  router:router 
}).$mount('#app')

 APP组件中   

  • <router-link> 配置跳转连接 ,router-link 最终会在 vue-router 的作用下转换为 a 标签
  •  <router-view></router-view> 标签展示页面
  •  以及 active-class="active"  完成下面的效果

 

<template>
  <div>
    <div class="row">
      <div class="col-xs-offset-2 col-xs-8">
        <div class="page-header"><h2>Vue Router Demo</h2></div>
      </div>
    </div>
    <div class="row">
      <div class="col-xs-2 col-xs-offset-2">
        <div class="list-group">
          <!-- <a class="list-group-item active" href="./about.html">About</a>
          <a class="list-group-item" href="./home.html">Home</a> -->

          <!--1 -router-link 标签实现切换-->
          <router-link class="list-group-item " active-class="active"  to="/about">About</router-link>
          <router-link class="list-group-item" active-class="active" to="/home">Home</router-link> 
        </div>
      </div>
      <div class="col-xs-6">
        <div class="panel">
          <div class="panel-body">
           <!--2 -router-view 标签完成展示-->
              <router-view></router-view>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

export default {
  name: "App",
};
</script>

<style lang="css">

</style>

 ./src/pages 文件夹下面新建About组件 和Home组件(2个一样)

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

<script>
export default {
    name:'About'
}

</script>

<style>

</style>

三、嵌套路由

完成如下效果,在Home组件下面添加子路由

src\router\index.js  配置多级路由,如下 1 、2处

注意:

  • children 属性配置多级路由
  • 一级路由后面的二级路由、三级路由等前面都不需要添加斜
// 该文件专门用于创建整个路由器
import VueRouter from 'vue-router'

// 引入组件
import About from '../pages/About'
import Home from '../pages/Home'

import Message from '../pages/Message'
import News from '../pages/News'

// 创建并暴露一个路由器
export default new VueRouter({
    routes: [
        {
            path: '/about',
            component: About
        },
        {
            path: '/home',
            component: Home,
            // 1- 通过children 配置子级路由
            children: [
                {
                    path: 'message',  //2 一级路由后面的二级路由、三级路由等前面都不需要添加斜杆'/'
                    component: Message
                },
                {
                    path: 'news',
                    component: News
                },
            ]
        }
    ]
})

Home组件下面代码,如下

注意 :

to="/home/news  要匹配到 路由

<template>
  <div>
    <div>
      <h2>Home组件内容</h2>
      <div>
        <ul class="nav nav-tabs">
          <!--1- router-link 配置路由   注意: to="/home/news -->
          <li>
            <router-link class="list-group-item" active-class="active" to="/home/news">News</router-link>
          </li>
          <li>
            <router-link class="list-group-item" active-class="active" to="/home/message">Message</router-link>
          </li>
        </ul>
     <!-- 2- router-view 展示页面-->
     <router-view></router-view>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "Home",
};
</script>

<style>
</style>

Message 、News组件 如下

<template>
  <div>
    <ul>
      <li><a href="/message1">message001</a>&nbsp;&nbsp;</li>
      <li><a href="/message2">message002</a>&nbsp;&nbsp;</li>
      <li><a href="/message/3">message003</a>&nbsp;&nbsp;</li>
    </ul>
  </div>
</template>

<script>
export default {
    name:'Message'
};
</script>

四、路由的query传参

message 组件,像detail传递参数 2种写法

  • 模板字符串写法
  • 对象写法
<template>
  <div>
    <ul>
      <li v-for="m in messageLsit" :key="m.id">
        <!-- 1- to传递参数  字符串写法一-->
        <router-link :to="`/home/message/detail?id=${m.id}&title=${m.title}`">{{ m.title }}</router-link> &nbsp;

         <!-- 1- to传递参数  对象写法 写法二-->
         <router-link :to="{
              path:'/home/message/detail', 
              query:{
                id:m.id,
                title:m.title
              }
            }">{{m.title}}</router-link>
      </li>
    </ul>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: "Message",
  data() {
    return {
      messageLsit: [
        { id: "001", title: "message1" },
        { id: "002", title: "message2" },
        { id: "003", title: "message3" },
      ],
    };
  },
};
</script>

detail 接受参数   $route 中获取

<template>
  <div>
    <ul>
        <!-- 接受参数 -->
        <li>消息编号:{{ $route.query.id }}</li>
        <li>消息内容:{{ $route.query.title }}</li>
    </ul>
  </div>
</template>

<script>
export default {
    name:'Detail'
}
</script>

<style>

</style>

 五、命名路由

给路由设置name属性,命名

// 该文件专门用于创建整个路由器
import VueRouter from 'vue-router'

// 引入组件
import About from '../pages/About'
import Home from '../pages/Home'

import Message from '../pages/Message'
import News from '../pages/News'

import Detail from '../pages/Detail'


export default new VueRouter({
    routes: [
        {
            // 1- 给about路由命名
            name:'guanyu',
            path: '/about',
            component: About
        },
        {
            path: '/home',
            component: Home,
        
            children: [
                {
                    path: 'message',  
                    component: Message,
                    children: [
                        {   
                            path: 'detail',
                            component: Detail
                        }
                    ]
                },
                {
                    path: 'news',
                    component: News
                },
            ]
        }
    ]
})

跳转处写法

   <!--1 -router-link 标签实现切换-->
          <router-link class="list-group-item" active-class="active" :to="{name:'guanyu'}">About</router-link

六、路由的params参数

params 传递参数的2种写法

1- 模板字符串

2- 对象写法 (注意: path 会报错,只能用name 去跳转

<template>
  <div>
    <ul>
      <li v-for="m in messageLsit" :key="m.id">
        <!-- 1- params 传递参数 字符串写法-->
        <router-link :to="`/home/message/detail/${m.id}/${m.title}`">{{ m.title }}</router-link> &nbsp;

         <!-- 2- params传递参数  对象写法 写法二 (此处只能用name)-->
         <router-link :to="{
              name:'xiangqing', 
              params:{
                id:m.id,
                title:m.title
              }
            }" >{{m.title}}</router-link>
      </li>
    </ul>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: "Message",
  data() {
    return {
      messageLsit: [
        { id: "001", title: "message1" },
        { id: "002", title: "message2" },
        { id: "003", title: "message3" },
      ],
    };
  },
};
</script>

src\router\index.js 路由文件的写法

// 该文件专门用于创建整个路由器
import VueRouter from 'vue-router'
// 引入组件
import About from '../pages/About'
import Home from '../pages/Home'
import Message from '../pages/Message'
import News from '../pages/News'
import Detail from '../pages/Detail'
export default new VueRouter({
    routes: [
        {
            name:'guanyu',
            path: '/about',
            component: About
        },
        {
            path: '/home',
            component: Home,
        
            children: [
                {
                    path: 'message',  
                    component: Message,
                    children: [
                        {   
                            //1- params 参数定义
                            name:'xiangqing',
                            //2- 声明占位 传递参数
                            path: 'detail/:id/:title',
                            component: Detail
                        }
                    ]
                },
                {
                    path: 'news',
                    component: News
                },
            ]
        }
    ]
})

Detail组件接受参数

   <li>消息编号:{{ $route.params.id }}</li>
        <li>消息内容:{{ $route.params.title }}</li>

七、路由的 props 配置

作用:让路由组件更方便收到值

  • 写法一只能配置并传递固定数据
  • 写法二只能接收路由传递过来的 params 参数
  • 写法三灵活性最大,可以通过 $route 来传递 query 或者 params 参数

src\router\index.js 文件中 props 三种写法

// 该文件专门用于创建整个路由器
import VueRouter from 'vue-router'
// 引入组件
import About from '../pages/About'
import Home from '../pages/Home'
import Message from '../pages/Message'
import News from '../pages/News'
import Detail from '../pages/Detail'
export default new VueRouter({
    routes: [
        {
            name: 'guanyu',
            path: '/about',
            component: About
        },
        {
            path: '/home',
            component: Home,

            children: [
                {
                    path: 'message',
                    component: Message,
                    children: [
                        {
                            name: 'xiangqing',
                            path: 'detail/:id/:title',
                            component: Detail,
                            //1- props 第一种写法 ,传递对象
                            //  props:{a:100,b:'message100'}
                            //2-props 第二种写法 ,布尔值为真,把路由收到params参数按照props传给组件
                            // props: true
                            // 第三种写法,props 值为函数,该函数返回的对象中每一组 key-value 都会通过 props 传给 Detail 组件
                            // query传参
                            // <router-link :to="{
                            //     name:'xiangqing', 
                            //     query:{
                            //       id:m.id,
                            //       title:m.title
                            //     }
                            //   }" >{{m.title}}</router-link>
                            props($route) {
                                return {
                                    id: $route.query.id,
                                    title: $route.query.title,
                                }
                            }

                        }
                    ]
                },
                {
                    path: 'news',
                    component: News
                },
            ]
        }
    ]
})

 Detail 接受参数的写法

<template>
  <div>
    <ul>
        <!-- 3- param 接受参数 -->
        <li>消息编号:{{id }}</li>
        <li>消息内容:{{title }}</li>

        <!-- <li>路由props对像: {{ a }}</li>
        <li>路由props对像: {{ b }}</li> -->

    </ul>
  </div>
</template>

<script>
export default {
    name:'Detail',
    //1-
    // props:['a','b']
    //2-
    props:['id','title']
}
</script>

<style>

</style>

八、router-link 的 replace 属性

作用:控制路由跳转时操作浏览器历史记录的模式

浏览器的历史记录有两种写入方式:

  • push 是追加历史记录
  • replace 是替换当前历史记录
  • 路由跳转时默认是 push

 开启replace 模式

<router-link replace …>News</router-link>

 九、编程式路由导航

作用:不借助 <router-link> 实现路由跳转,让路由跳转更加灵活

 message组件编写按钮跳转路由 借,助this.$router 中的提供的api实现,如下 1、 2 代码处

<template>
  <div>
    <ul>
      <li v-for="m in messageLsit" :key="m.id">
        <!-- <router-link :to="`/home/message/detail/${m.id}/${m.title}`">{{ m.title }}</router-link> &nbsp; -->

        <router-link
          :to="{
            name: 'xiangqing',
            query: {
              id: m.id,
              title: m.title,
            },
          }"
          >{{ m.title }}</router-link
        >
        <!-- 1- 编写按钮 -->
        <button @click="showPush(m)">push查看</button>
      <button @click="showReplace(m)">replace查看</button>
      </li>
    
    </ul>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: "Message",
  data() {
    return {
      messageLsit: [
        { id: "001", title: "message1" },
        { id: "002", title: "message2" },
        { id: "003", title: "message3" },
      ],
    };
  },
  methods:{
    //2-  this.$router.push   this.$router.replace 实现跳转
    showPush(m) {
    this.$router.push({
      name: "xiangqing",
      query: {
        id: m.id,
        title: m.title,
      },
    });
  },
  showReplace(m) {
    this.$router.replace({
      name: "xiangqing",
      query: {
        id: m.id,
        title: m.title,
      },
    });
  },
  }
};
</script>

$router 路由器中还有如下的 API 可供我们前进和回退浏览器器历史记录

  • this.$router.forward()    // 前进
  • this.$router.back()        // 后退
  • this.$router.go(num)    // 前景或后退
     

<template>
  <div>
    <div class="col-xs-offset-2 col-xs-8">
        <div class="page-header"><h2>Vue Router Demo</h2></div>
      </div>
      <button @click="froward">前进</button>
      <button @click="back">后退</button>
      <button @click="go">test go</button>
  </div>
</template>

<script>
export default {
    name:'Banner',
    methods:{
      froward(){
        this.$router.forward()	// 前进
      },
      back(){
        this.$router.back()		// 后退
      },
      go(){
        this.$router.go(-2)		//  传入正数 往前跳转几页,负数往后跳转几页
      }
    }
}
</script>

<style>

</style>

十、缓存路由组件

作用让不展示的路由组件保持挂载,不被销毁

  • keep-alive 中不添加 include,那么将使得挂载到 router-view 中路由每次切换时都不会被销毁
  • keep-alive 的 include 的参数值为组件名,而不是路由名
  • 如果想要缓存多个组件,那么 include 里面的路由需要写成数组形式,例如 :include="['News', 'Message']"
<keep-alive include="News"> <router-view></router-view> </keep-alive>

 多个

     <keep-alive :include="['News', 'Message']">
          <router-view></router-view>
        </keep-alive>

十一、路由的钩子函数

作用:路由组件所独有的两个钩子函数,用于捕获路由组件的激活状态

  1. activated:路由组件被激活时触发
  2. deactivated:路由组件失活时触发
<template>
  <div>
    <ul>
      <li>news001<input type="text" /></li>
      <li>news002<input type="text" /></li>
      <li>news003<input type="text" /></li>

      <li :style="{opacity}">VUE生命周期</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "News",
  data() {
    return {
      opacity:1
    }
  },
  activated() {
    //1- 组件被激活时
    this.timeer = setInterval(() => {
				console.log('还在执行。。。。。');
				this.opacity -= 0.01;
				if (this.opacity <= 0) {
					this.opacity = 1;
				}
			})
  },
    //2- 组件失活时
  deactivated() {
    clearInterval(this.timeer)
  },
};
</script>

十二、路由守卫

1.全局守卫

1-  router.beforeEach((to, from, next) => {…}):全局前置守卫配置

  • to:目标路由
  • from:源路由
  • next:是一个回调函数,对后续的执行操作起着拦截或放行的作用

2- router.afterEach((to, from) => {…}):全局后置守卫配置

  • to:目标路由
  • from:源路由

使用场景

  • 前置守卫适用于路由改变前的操作,可以根据权限判断是否展示对应路由的信息
  • 后置守卫适用于路由改变后的操作,可以根据是否进入对应路由来执行相应的操作

下面展示点单DEMO  如 1、2、3处代码 

// 该文件专门用于创建整个路由器
import VueRouter from 'vue-router'
// 引入组件
import About from '../pages/About'
import Home from '../pages/Home'
import Message from '../pages/Message'
import News from '../pages/News'
import Detail from '../pages/Detail'
const router =  new VueRouter({
    routes: [
        {
            name: 'guanyu',
            path: '/about',
            component: About,
            meta:{
                isAuth:false,	//1- 用于表示该路由是否需要进行权限判断
            }
        },
        {
            name:'zhuye',
            path: '/home',
            component: Home,

            children: [
                {
                    path: 'message',
                    component: Message,
                    children: [
                        {
                            name: 'xiangqing',
                            path: 'detail/:id/:title',
                            component: Detail,
                            props($route) {
                                return {
                                    id: $route.query.id,
                                    title: $route.query.title,
                                }
                            }

                        }
                    ]
                },
                {
                    path: 'news',
                    component: News
                },
            ]
        }
    ]
})

// 2-全局前置路由守卫 —— 初始化的时候被调用以及每次路由切换的时候都会调用一次 
router.beforeEach((to, from, next) => {
    console.log('前置守卫', to, from)

    if(to.meta.isAuth) {    // 判断是否需要授权
        if(localStorage.getItem('school') === 'atguigu') {
            next()
        } else {
            alert('学校名不对,无权查看')
        }
    } else {
        next()  // 不需要判断权限的路由直接放行
    }
})

// 3-全局后置路由守卫
router.afterEach((to, from) => {    // 该配置是为了每次路由跳转的时候进行标签名的更新
    console.log('后置路由守卫', to, from);
    if(to.meta.title) {
        document.title = to.meta.title  // 如果 meta 中配置了路由的 title,那么就修改
    } else {
        document.title = 'vue-test'
    }
})


export default router;
2.独享路由守卫

作用:只对单个路由进行的守卫

独享路由守卫的配置函数为beforeEnter((to, from, next) => {…}) ,是在 route 中进行配置。

如图代码1处:

// 该文件专门用于创建整个路由器
import VueRouter from 'vue-router'
// 引入组件
import About from '../pages/About'
import Home from '../pages/Home'
import Message from '../pages/Message'
import News from '../pages/News'
import Detail from '../pages/Detail'
const router =  new VueRouter({
    routes: [
        {
            name: 'guanyu',
            path: '/about',
            component: About,
            meta:{
                isAuth:false,	
            }
        },
        {
            name:'zhuye',
            path: '/home',
            component: Home,

            children: [
                {
                    path: 'message',
                    component: Message,
                    children: [
                        {
                            name: 'xiangqing',
                            path: 'detail/:id/:title',
                            component: Detail,
                            props($route) {
                                return {
                                    id: $route.query.id,
                                    title: $route.query.title,
                                }
                            }

                        }
                    ]
                },
                {
                    path: 'news',
                    component: News,
                    //1-独享路由守卫
                    beforeEnter(to, from, next) {
                        console.log('独享路由守卫', to, from)
                    
                        if(to.meta.isAuth) {    // 判断是否需要授权
                            if(localStorage.getItem('school') === 'atguigu') {
                                next()
                            } else {
                                alert('学校名不对,无权查看')
                            }
                        } else {
                            next()  // 不需要判断权限的路由直接放行
                        }
                    }
                    
                },
            ]
        }
    ]
})



export default router;
3. 组件内路由守卫

作用:主要针对组件而言,在组件之间切换时触发的守卫

  1. // 进入守卫,通过路由规则,进入该组件时被调用 beforeRouteEnter(to, from, next) {},
  2. // 离开守卫,通过路由规则,离开该组价时被调用 beforeRouteLeave(to, from, next) {},

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

<script>
export default {
  name: "About",
  //1- 进入守卫,通过路由规则,进入该组件时被调用
  beforeRouteEnter(to, from, next) {
    console.log("组件内路由守卫", to, from);
    if (to.meta.isAuth) {
      if (localStorage.getItem("school") === "atguigu") {
        next();
      } else {
        alert("学校名不对,无权查看");
      }
    } else {
      next(); // 不需要判断权限的路由直接放行
    }
  },
  // 2- 离开守卫,通过路由规则,离开该组价时被调用
  beforeRouteLeave(to, from, next) {},
};
</script>

<style>
</style>

十三、路由工作模式 hash、history

1、路由器存在两种工作模式:

  1. history 模式
  2. hash 模式

对于一个 url 来说,hash 指的就是 # 后面的内容,hash 值不会包含在 HTTP 请求中,即 hash 值不会带给服务器 

特点

1-hash 模式(默认
地址中永远带这 # 号,不美观
若以后将地址通过第三方手机 app 分享,若 app 检验严格,则地址会被标记为不合法
2-history 模式
地址干净、美观
兼容性和 hash 模式相比略差
应用部署上线时需要后端人员支持,解决刷新页面服务器 404 的问题(一般 nginx 解决)
 

 1- 修改模式方法

在创建路由器 router 对象实例中添加 mode:history 或者 mode:hash 来将路由模式修改为 history 或 hash 模式

const router = new VueRouter({
    mode:'history',
    routes: […]
})
 2、打包测试

了演示 hash 模式下,hash 值不会带给服务器,我们需要将之前制作的 SPA 进行打包,打包命令如下: 

        npm run build

 稍事等待,待打包完毕后,生成的文件在 /dist 文件夹中,生成的目录结构如下:

dist                                 
├─ css                               
│  └─ bootstrap.css                  
├─ js                                
│  ├─ app.adc4f030.js                
│  ├─ app.adc4f030.js.map            
│  ├─ chunk-vendors.7c6bdce6.js      
│  └─ chunk-vendors.7c6bdce6.js.map  
├─ favicon.ico                       
└─ index.html                        
 

上面打包文件,直接打开 index.html ,肯定是浏览器不了的,需要将打包的文件放到服务器中服务才能运行,所以我们现在来使用 node.js 和 express 来编写一个服务器

1-安装 express 框架,npm i express

 2-编写一个服务器主文件 /server.js

const express = require('express')  // 使用 common.js 的语法来引入 express 框架
// 创建 app 服务实例对象
const app = express()
// 指定静态资源
app.use(express.static(__dirname + '/static'))
// 搭建路由
app.get('demo', (req, res) => {
    res.send({
        name:'tom',
        age:18,
    })
})

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

  • 新建一个 static 文件夹,用于存放静态资源,将生成好的 dist 文件夹中的内容放置到 static 中

  • 启动服务器:node server

  • 在浏览器中输入 localhost:5005 打开部署好的页面

 history 404问题

如果面对 history 模式,我们也有自己的解决方法,首先去 npm 包管理平台 下载 connect-history-api-fallback,或者使用如下命令安装:

                npm i connect-history-api-fallback

const history = require('connect-history-api-fallback')

// 注释使用 history 的时机,需要在创建 app 实例之后,在挂载静态资源之前
app.use(history())

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值