Vue —— 精讲 VueRouter(1)

最近被Boos调去给新人做培训去了,目前把自己整理的一些东西分享出来,希望对大家有所帮助

demo源代码地址:https://github.com/BM-laoli/BMlaoli-learn-VueRouter

本章节为VueRouter前端 路由的章节部分

大纲

一、基本概念

路由就是通过网络把讯息从源地址传输到目的地的活动
需要一些映射表

  1. 做路由
  2. 做信息的转发(核心就是:转发)

后端路由还有前端路由,后端渲染和前端渲染

前端渲染(前后端分离API生态),后端渲染(view嵌套一起)

前端路由的核心概念
地址变化的时候改变url的时候,不进行整体页面刷新

改变url但是不刷新页面,的解决方式

我们有这样的一个需求,改变url跳转地址,我们获取新的页面,但是不希望页面发生刷新

解决方案1:locaion.hash = '/'

这个是vueRouter的底层实现

监听hash的变化,从而改变网页数据的获取机制,渲染对应的组件,

解决方案2:H5的histroray模式

  1. pushState
    history.pushState({},'','home'),第三个参数就是url

这里的push实际上就是一个栈结构(先进后出),

假设我们这里需要回去,使用back()弹栈

history.pushState({},'','home'),
history.pushState({},'','about'),
history.pushState({},'','user'),

//执行这个之后就能进行back()出栈了
history.back(),
// 此时的url是 /about

  1. repalceState

这里有一个方法和push方法很像,但是不会back()不能点击后腿按钮

history.repalceState({},'','user'),
  1. go

这里的go是对栈的一个操作,
go(-1)弹出一个
go(-2)弹出二个

go(1)压入一个
go(2)压入二个

go(-1)

以上就是我们的基本的前端路由原理

二、v-router基本使用

前端三大框架都有自己的router,可以用来构建SPA应用

使用小提示,还是非常非常的简单的:

  1. 如果你没有安装就需要 npm install vue-router去安装
    • 导入路由对象,并且调用Vue.use(VueRouter)安装这个路由插件
    • 创建路由实例,传入映射配置wxain
    • 在vue实例中挂载创建好了的路由

1.导入路由对象,并且配置optionn给路由

/router/index.js


/**
 * 配置路由相关的信息
 */
// 1. 导入
 import Router from 'vue-router'
 
 // 2.1 导入vue实例
import Vue from 'vue'

// 导入组件
import Home from '../components/Home.vue'
import About from '../components/About.vue'


// 2.2使用路由(插件),安装插件,vue的插件,都是这样安装,Vue.use
Vue.use(Router)

// 3. 创建路路由对象,这个就是在Router里面配置映射和对象等东西

// 4. 抽离配置项出来
const routes = []

const router = new Router({routes})

//4. 导出
export default router 
 

2.配置路由映射

/router/index.js

const routes = [
 
 {path:'/home',component:Home},
 {path:'/about',component:About},

] 

3.在实例中使用路由

/main.js

import Vue from 'vue'
import App from './App'
import router from './router'//注意啊模块查找规则index.js

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,// 主要是在这里挂载进去就好了
  render: h => h(App)
}) 

/App.vue


<template>
  <div id="app">
    <!-- //这两个是一个全局祖册过着个组件,这个就是一个a标签 -->
    <router-link to='/home'>首页</router-link>
    <router-link to='/about'>关于</router-link>
    <!-- 路由出口,既:渲染的出口,这个就是一个占位符号 -->
    <router-view></router-view>
  </div>
</template>

以下是我们的两个组件

/Home.vue

<template>
    <div>
        <h2>我是首页</h2>
        <p>我是首页内容哈哈哈</p>
    </div>
</template>

<script>
    export default {
        
    }
</script>

<style scoped>

</style>

/About.vue

<template>
    <div>
        <h2>我是关于页面</h2>
        <p>我是首关于内容哈哈哈</p>
    </div>
</template>

<script>
    export default {
        
    }
</script>

<style>

</style>

以上就是我们非常简单的使用

三、其它的知识点补充

路由的默认值,并且修改成mode=>hisary模式

我们希望默认显示的就是一个首页
解决方式,映射一个'/’,然后进行重定向
/index.js

  {
    path:'/',
    redirect:'/home'
  },

我们为什么要去做这调整成一个history,因为我们希望去掉#这个标识

只需要在new 的时候指定一下就好了
/index,js

const router = new Router({
  routes,
  mode:"history"//就是这里的这个更改路由方式
})

router-link的属性

  1. tage
    to是一个属性 ,默认是渲染成一个a链接,假设我现在需要默认渲染成一个buttmm怎么办呢?
    加一个tag就好了
    <router-link to='/home' tag='button'  >首页</router-link>
  1. 更改模式replceStats 不允许浏览器回退
    replace加上去就好了
<router-link to='/about' tag='button' replace >关于</router-link>
  1. 我们可以利用一些默认的东西去非常方便的做到想要的效果
<style>
.router-link-active{
  color: blue;
}
</style>

替换值:我们希望不要怎么长,我们希望.active就能改样式怎么搞?
加一个active-calss就好了,这个直接就是acitve做为类就好了

 <router-link to='/home' tag='button'  active-class  >首页</router-link>
 <style>
    .active{
        bgc:red
    }
 </style>

代码路由跳转,意思就是重定向

注意啊!route != router
在我们学习路由的时候,this.$router是一个非常重要的对象

这个东西在开中经常的使用

// this.$router.push('重定向的值就好了')。
// this.$router.push('/home')
// 如果你不想有出现回退按钮,这样来做就好了
this.$router.replace('/home')

四、动态路由参数

这里只是简单的介绍了理由传参的地址栏拼接模式,但是还有更多更奇奇怪怪的传值方式,详见官方Router文档,

this.$router.parmas
// 这个parmas里面就是我们的路由参数存放点

这里我们有这样的一个需求,我们希望点击user页面的时候可以,得到任意的路由参数

比如我们现在/user/zhnsang,的时候可以获取zhangshang,/user/lishi的时候可以获取lishi>

  1. 首先我们需要在路由里面加:
    /router/index.js
   {
        path: "/user/:usermsg",
        component: User
    }
]
  1. 页面传递数据
    /App.vue
router-link :to="'/user/'+username">用户相关</router-link>
<!-- 路由出口,既:渲染的出口,这个就是一个占位符号 -->
<router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      username: 'lisi'
    }
  },

  1. 页面获取数据

一定要注意了,一定是rouer里面定义的才能从另一路由拿出来

/User.vue


<template>
    <div>
        <h2>我是用户相关专业</h2>
        <p>我是用户讯息相关页面,嘿嘿嘿嘿嘿</p>
        <h1>{{ $route.params.usermsg }}44</h1>
        <hr>
        <h2>{{username}}</h2>
    </div>
</template>

<script>
    export default {    
        computed: {
            username() {
                return this.$route.params.usermsg
            }
        },
    }
</script>

<style scpoe>

</style>

五、细节详解

注意啊!再说一遍route != router

注意啊,这里的$route实际上是我们在main里面new的一个Router得到的,
并且 这个route对象是随着请求的地方不一样,而改变的。也就是说,这个的route是当前页面中的route对象,而且在vue只能只有一个route实例存在

六、 Vue的webpack打包详解 + 路由懒加载

一个vue项目的简单打包目录结构分析

我们来看看,在一个vue项目中,简单的三个文件是怎么打包的

假设目前有这样的三个文件 ,我们需要对他们进行打包,mian是入口,有一个add业务,有一个math依赖模块。那么我们webpack打包成的三个文件到底是如何运行的呢?

在vue中 使用webpack打包的时候,会把一些东西给分模块的打包出来,它打包的东西的目录结构如下
里面我们实际打包的时候会把css,js都给分开,各自有各自的作用

| dist
| ---static
| ---css
| ---js
| -----app.XXXX.js         (这个是项目的业务逻辑所在)
| -----manifest.xxxx.js    (这个是底层打包的依赖文件所在)
| -----vendor.xxxx.js      (这个是依赖所在)
| idnex.html

路由懒加载

  1. 概念的理解

目前呢,我们打包的情况是这样的:我们所有的代码都是集中放在了以一个app.xxx.js文件中,这样其实不利于后期的维护和开发,因为如果我们有很多很多的大量的代码的时候,我们的这个文件就会变得非常非常的大,于是呢,我们就需要路由懒加载,所谓懒加载就是:‘在需要的时候,才去加载某个资源文件’,路由懒加载,就是把每一个路由对应的业务逻辑代码,在打包的时候分割到不同的js文件中,如何在需要用的时候再去请求它

经过这样的打包的懒加载之后,我们的目录会变成这个样子

| dist
| ---static
| ---css
| ---js
| -----0.xxx.js            (假设是路由home的业务逻辑代码)
| -----1.xxx.js             (假设是路由about的业务逻辑代码)
| -----app.XXXX.js         (这个是项目的业务逻辑所在)
| -----manifest.xxxx.js    (这个是底层打包的依赖文件所在)
| -----vendor.xxxx.js      (这个是依赖所在)
| idnex.html
  1. 如何使用

使用非常的简单,主要有如下的三种方式去使用,但是我最喜欢的还是最后一种方式
/rouetr/index.js

- 使用vue的异步组价和webpack的写法,早期的时候
const Home = resolve =>{ require.ensure(['../compenet/Home.vue'],()=>{
   resolve (require('../compenet/Home.vue'))
})}

- AMD规范的写法
const About = resolve =>{ require(['../compenent/About.vue'],resolve) }


- ES6的结合异步组件的方式(最常用)
const Home = () => import('../compenet/Home.vue')

实际的使用
/router/index.js

/**
 * 配置路由相关的信息
 */
// 1. 导入
import Router from 'vue-router'

// 2.1 导入vue实例
import Vue from 'vue'

// 导入组件
// import Home from '../components/Home.vue'
// import About from '../components/About.vue'
// import User from '../components/User'
const Home = () =>
    import ('../components/Home.vue')
const About = () =>
    import ('../components/About.vue')
const User = () =>
    import ('../components/User')


// 2.2使用路由(插件),安装插件,vue的插件,都是这样安装,Vue.use
Vue.use(Router)

// 3. 创建路路由对象,这个就是在Router里面配置映射和对象等东西

// 4. 抽离配置项出来
const routes = [{
        path: '/',
        redirect: '/home'
    },
    {
        path: '/home',
        component: Home
    },
    {
        path: '/about',
        component: About
    },
    {
        path: "/user/:usermsg",
        component: User
    }
]

const router = new Router({
    routes,
    mode: "history"
})

//4. 导出
export default router

//6. 去main里面挂载

七、 路由嵌套

我们目前有这样的一个需求:我们希望我们在hone下,可以/home/new去到home下的一个子组件,/home/message去到另一个子组件

  1. 首先 我们需要有组件
    /components/HomeMessage.vue
<template>
    <div>
      <ul>
          <li1>我是消息1</li1>
          <li2>我是消息2</li2>
          <li3>我是消息3</li3>
          <li4>我是消息4</li4>
      </ul>
    </div>
</template>

<script>
    export default {
        name:"HomeMessage"
    }   
</script>

<style>

</style>

/components/HomeNews

<template>
    <div>
    <ul>
        <li1>新1</li1>
        <li2>新2</li2>
        <li3>新3</li3>
        <li4>新4</li4>
        <li5>新5</li5>
    </ul>
    </div>
</template>

<script>
    export default {
        name:"HomeNews"
    }
</script>

<style>

</style>
  1. 在路由里面去配置
const HomeNews = () =>
    import ('../components/HomeNews')
const HomeMessage = () =>
    import ('../components/HomeNews')


// 2.2使用路由(插件),安装插件,vue的插件,都是这样安装,Vue.use
Vue.use(Router)

// 3. 创建路路由对象,这个就是在Router里面配置映射和对象等东西

// 4. 抽离配置项出来
const routes = [{
        path: '/',
        redirect: '/home'
    },
    {
        path: '/home',
        component: Home,
        children: [{
                path: '',
                redirect: 'news'
            },
            {
                path: 'news',// 这里写路由实际上应该是/home/news,这里只是一个相对路由地址,
                component: HomeNews
            },
            {
                path: 'message',
                component: HomeMessage
            },

        ]
    },
    {
  1. 打入口router-view(瞎起的名字实际上就是路由的占位符)
    /Home.vue
<template>
    <div>
        <h2>我是首页</h2>
        <p>我是首页内容哈哈哈</p>
     <router-link to="/home/news">news</router-link>
     <router-link to="/home/message">message</router-link>
    <router-view></router-view>
    </div>
</template>

<script>
    export default {
        
    }
</script>

<style scoped>

</style>

这里如果是有关状态的保持,我们需要使用key-alive,后面我们再做详细的讲解

posted @ 2020-06-14 08:39  BM老李  阅读(576)  评论(0编辑  收藏  举报