doina

一个小菜鸟运维工程师.

vue-route基本使用

[toc]

路由介绍

  • 路由(routing)就是通过互联的网络把信息从源地址传输到目的地址的活动.
  • 路由器提供了两种机制: 路由和转送.
    • 路由是决定数据包从来源到目的地的路径
    • 转送将输入端的数据转移到合适的输出端.
  • 路由中有一个非常重要的概念叫路由表.
    • 路由表本质上就是一个映射表, 决定了数据包的指向

后端路由阶段

  • 早期的网站开发整个HTML页面是由服务器来渲染的.
    • 服务器直接生产渲染好对应的HTML页面, 返回给客户端进行展示.
  • 但是, 一个网站, 这么多页面服务器如何处理呢?
    • 一个页面有自己对应的网址, 也就是URL.
    • URL会发送到服务器, 服务器会通过正则对该URL进行匹配, 并且最后交给一个Controller进行处理.
    • Controller进行各种处理, 最终生成HTML或者数据, 返回给前端.
    • 这就完成了一个IO操作.
  • 上面的这种操作, 就是后端路由.
    • 当我们页面中需要请求不同的路径内容时, 交给服务器来进行处理, 服务器渲染好整个页面, 并且将页面返回给客户顿.
    • 这种情况下渲染好的页面, 不需要单独加载任何的js和css, 可以直接交给浏览器展示, 这样也有利于SEO的优化.
  • 后端路由的缺点:
    • 一种情况是整个页面的模块由后端人员来编写和维护的.
    • 另一种情况是前端开发人员如果要开发页面, 需要通过PHP和Java等语言来编写页面代码.
    • 而且通常情况下HTML代码和数据以及对应的逻辑会混在一起, 编写和维护都是非常糟糕的事情.

前后端分离阶段

  • 前后端分离阶段:
    • 随着Ajax的出现, 有了前后端分离的开发模式.
    • 后端只提供API来返回数据, 前端通过Ajax获取数据, 并且可以通过JavaScript将数据渲染到页面中.
    • 这样做最大的优点就是前后端责任的清晰, 后端专注于数据上, 前端专注于交互和可视化上.
    • 并且当移动端(iOS/Android)出现后, 后端不需要进行任何处理, 依然使用之前的一套API即可.
    • 目前很多的网站依然采用这种模式开发.

前端路由阶段

  • 单页面富应用阶段:
    • 其实SPA最主要的特点就是在前后端分离的基础上加了一层前端路由.
    • 也就是前端来维护一套路由规则.
  • 前端路由的核心是什么呢?
    • 改变URL,但是页面不进行整体的刷新。
  • 目前前端流行的三大框架, 都有自己的路由实现:
    • Angular的ngRouter
    • React的ReactRouter
    • Vue的vue-router

vue-router 学习

  • vue-router是基于路由和组件的
    • vue-router是Vue.js官方的路由插件,它和vue.js是深度集成的,适合用于构建单页面应用。
    • 我们可以访问其官方网站对其进行学习: https://router.vuejs.org/zh/
    • 路由用于设定访问路径, 将路径和组件映射起来.
    • 在vue-router的单页面应用中, 页面的路径的改变就是组件的切换.

改变url页面不刷新的两种模式

改变url, 不请求服务器重新刷新页面

URL的hash模式

location.hash = 'home'

HTML5的history模式:pushState

# 修改成新的url, 相当于进栈
history.pushState({}, '', 'about')

# 直接替换url, 不进栈
history.replaceState({}, '', 'home')

# 返回上一次的url, 相当于出栈
history.back()

# 返回特定前进后退的步数
# -1 相当于 back(), 可以是-2, 也可以是2
history.go()

vue-route安装

安装

  1. 使用脚手架初始化项目时已经安装了vue-route, 没安装的话使用下面命令安装
// 运行时依赖
npm install vue-route@3.0.1 --save
  1. 在模块化工程中使用它(因为是一个插件, 所以可以通过Vue.use()来安装路由功能)

– 第一步:导入路由对象,并且调用 Vue.use(VueRouter)
– 第二步:创建路由实例,并且传入路由映射配置
– 第三步:在Vue实例中挂载创建的路由实例

使用

路由使用实例

src/route/index.js文件

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Home from '../components/home'
import About from '../components/about'

// 1. 通过Vue.use安装插件
Vue.use(Router)

// 2. 将下面的router拆除出来,单独创建VueRoute对象
const routes= [
  {
    path: '/',
    // 访问url为/的时候, 调整到/home
    redirect: '/home'
  },
  {
    path: '/home',
    component: Home
  },
  {
    path: '/about',
    component: About
  },
  {
    path: '/helloWorld',
    component: HelloWorld
  }

]

// 3. 创建VueRoute对象
const router = new Router({
  // 配置路径和组件的应用关系
  routes
})

// 4.将router对象传入到Vue实例
export default router

src/main.js

// 导入vue模块
import Vue from 'vue'
// 导入App组件
import App from './App'
// 导入路由配置
import router from './router'

Vue.config.productionTip = false

/* eslint-disable no-new */
// 创建新的Vue实例
new Vue({
  // 挂载到app实例
  el: '#app',
  // 挂载路由配置
  router,
  // 使用ontime-olny方式运行
  render: h => h(App)
})

src/componests/about.vue

<template>
  <div>
    <h2>我是about组件</h2>
    <p>我是about组件的内容</p>
  </div>
</template>

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

<style scoped>
h2 {
  color: chartreuse;
}
</style>

src/componests/home.vue

<template>
<div>
  <h2>我是Home组件</h2>
  <p>我是Home组件的内容</p>
</div>
</template>

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

<style scoped>
h2 {
  color: red;
}
</style>

src/componests/HelloWorld.vue

<template>
  <div class="hello">
    <!--添加到这里, 否则会找不到logo-->
    <img src="../assets/logo.png">
    <h1>{{ msg }}</h1>

npm run dev

《vue-route基本使用》

修改vue路由模式: History(去掉#号)

src/router/index.js

export default new Router({
  routes,
  // 修改路由模式为history
  mode: "history"
})

router-link的常用属性

const router = new Router({
  // 配置路径和组件的应用关系
  routes,
  mode: "history",
  // 自定义router-link-active的名称
  linkActiveClass: "active"
})
<template>
  <div id="app">
    <!-- 将标签修改成 button类型 -->
    <router-link to="home" tag="button">Home</router-link>
    <!-- 将标签修改成 button类型 -->
    <router-link to="about" tag="button">About</router-link>
    <!-- 将标签修改成 li类型 -->
    <router-link to="helloWorld" tag="li">helloWorld</router-link>
    <router-view></router-view>
  </div>
</template>

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

<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;
}

// 选中变成红色
.active {
  color: red;
}</style>

《vue-route基本使用》

通过代码实现路由跳转

src/App.vue

<script>
export default {
  name: 'App',
  methods: {
    homeClice() {
      this.$router.push('/home')
      console.log("homeClice");
    },
    aboutClick() {
      this.$router.push('/about')
      console.log("aboutClick");
    }
  }
}
</script>

动态路由使用

  • 在某些情况下,一个页面的path路径可能是不确定的,比如我们进入用户界面时,希望是如下的路径:
    • /user/1或/user/2
    • 除了有前面的/user之外,后面还跟上了用户的ID
    • 这种path和Component的匹配关系,我们称之为动态路由
  • params的类型:
    • 配置路由格式: /router/:id
    • 传递的方式: 在path后面跟上对应的值
    • 传递后形成的路径: /router/123, /router/abc
  • query的类型:
    • 配置路由格式: /router, 也就是普通配置
    • 传递的方式: 对象中使用query的key作为传递方式
    • 传递后形成的路径: /router?id=123, /router?id=abc
  • $route和$router是有区别的
    • $router为VueRouter实例,想要导航到不同URL,则使用$router.push方法
    • $route为当前router跳转对象里面可以获取name、path、query、params等

params: 路径参数

src/route/index.js

import User from "../components/User";

  {
    // 定义动态路由, userId在后面会用到
    path: '/user/:userId',
    component: User
  }

src/App.vue

<template>
  <div id="app">
    <!--通过动态绑定, 获取userId实际的值, 然后去跳转到对应的路由-->
    <router-link :to="'/user/'+userId" tag="button">用户信息</router-link>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return{
      // 返回userId
      userId: 110,
    }
  }
}
</script>

src/conponents/User.vue

<template>
<div>
  <h2>我是User组件</h2>
  <!--获取路由参数中的userId参数
  <p>我的ID是: {{$route.params.userId}}</p>
</div>
</template>

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

<style scoped>

</style>

《vue-route基本使用》

query: 请求参数

route-link实现

src/App.vue

<template>
  <div id="app">
    <!--给to传递一个对象,path和路由中的对应, query为请求的参数, 也可以直接在写参数, 我是在下面定义了一个对象,直接传到这里-->
    <router-link :to="{path: '/profile', query: queryArgs}" tag="button">参数传递</router-link>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return{
      userId: 110,
      queryArgs: {
        name: 'baiyongjie',
        age: '23',
        blog: 'https://baiyongjie.com'
      }
    }
  }
}
</script>

<style>
.active {
  color: red;
}
</style>

src/router/index.js

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

const Profile = () => import('../components/Profile')

const routes= [
  {
    path: '/profile',
    component: Profile
  }
]

export default new Router({
  routes,
  mode: "history",
  linkActiveClass: "active"
})

src/components/Profile.vue

<template>
<div>
  <h2>我是Profile组件</h2>
  <!--从$route.query对象中获取请求参数-->
  <h4>直接使用对象属性展示</h4>
  <p>姓名: {{$route.query.name}}</p>
  <p>年龄: {{$route.query.age}}</p>
  <p>博客: {{$route.query.blog}}</p>

  <ul>
    <h4>通过v-for循环展示</h4>
    <li v-for="(value, key) in $route.query">{{key}}: {{value}}</li>
  </ul>

</div>
</template>

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

<style scoped>

</style>

通过监听事件实现

src/App.vue

<template>
  <div id="app">
    <button @click="queryClick">参数传递</button>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return{
      userId: 110,
      queryArgs: {
        name: 'baiyongjie',
        age: '23',
        blog: 'https://baiyongjie.com'
      }
    }
  },
  methods: {
    queryClick() {
      this.$router.push({
        path: '/profile',
        query: this.queryArgs
      })
    }
  }
}
</script>

<style>
.active {
  color: red;
}
</style>

src/router/index.js

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

const Profile = () => import('../components/Profile')

const routes= [
  {
    path: '/profile',
    component: Profile
  }
]

export default new Router({
  routes,
  mode: "history",
  linkActiveClass: "active"
})

src/components/Profile.vue

<template>
<div>
  <h2>我是Profile组件</h2>
  <h4>直接使用对象属性展示</h4>
  <p>姓名: {{$route.query.name}}</p>
  <p>年龄: {{$route.query.age}}</p>
  <p>博客: {{$route.query.blog}}</p>

  <ul>
    <h4>通过v-for循环展示</h4>
    <li v-for="(value, key) in $route.query">{{key}}: {{value}}</li>
  </ul>

</div>
</template>

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

<style scoped>

</style>

《vue-route基本使用》

路由的懒加载

当打包构建应用时,Javascript 包会变得非常大,影响页面加载。
如果我们能把不同路由对应的组件分割成不同的代码块,然后当路由被访问的时候才加载对应组件,这样就更加高效了

  • 路由懒加载
    • 路由懒加载的主要作用就是将路由对应的组件打包成一个个的js代码块
    • 只有在这个路由被访问到的时候, 才加载对应的组件
  • 路由懒加载语法:
    • 一: 结合Vue的异步组件和Webpack的代码分析.
    • const Home = resolve => { require.ensure(['../components/Home.vue'], () => { resolve(require('../components/Home.vue')) })};
    • 方式二: AMD写法
    • const About = resolve => require(['../components/About.vue'], resolve);
    • 方式三: 在ES6中, 我们可以有更加简单的写法来组织Vue异步组件和Webpack的代码分割.
    • 定义变量,然后在component中引用: const Home = () => import('../components/Home.vue')
    • 直接在component中使用: component: () => import('../components/Home.vue'),

src/router/index.js

import Vue from 'vue'
import Router from 'vue-router'

// 1. 通过Vue.use安装插件
Vue.use(Router)

// 在这里导入, 然后在下面引用, 或者在下面component中直接引用也可以
const About = () => import('../components/About')
const User = () => import('../components/User')

// 2. 将下面的router拆除出来,单独创建VueRoute对象
const routes= [
  {
    path: '/',
    redirect: '/helloWorld'
  },
  {
    path: '/helloWorld',
    component: () => import('../components/HelloWorld')
  },
  {
    path: '/home',
    component: () => import('../components/Home')
  },
  {
    path: '/about',
    component: About
  },
  {
    path: '/user/:userId',
    component: User
  }
]

// 3. 创建VueRoute对象,并导出,然后在vue实例中挂载
export default new Router({
  // 配置路径和组件的应用关系
  routes,
  mode: "history",
  linkActiveClass: "active"
})

npm run build

> npm run build

Hash: 34df25c719c6ee11f9e8
Version: webpack 3.12.0
Time: 11680ms
                                                  Asset       Size  Chunks             Chunk Names
                    static/js/0.db4a749397b58d06ec83.js    11.2 kB       0  [emitted]
                    static/js/1.a3e3b4daaa5b3ce912a9.js  550 bytes       1  [emitted]
                    static/js/2.1120d25dace1a3c02081.js  507 bytes       2  [emitted]
                    static/js/3.395f900be5a61e751d87.js  549 bytes       3  [emitted]
               static/js/vendor.bbddf67a6696c765f88f.js    94.2 kB       4  [emitted]  vendor
                  static/js/app.9e45a1d5c470dbc4056b.js    1.34 kB       5  [emitted]  app
             static/js/manifest.93a29dadc6f6f8fc031c.js    1.53 kB       6  [emitted]  manifest
    static/css/app.05222d776249e64862bd4957a923bd69.css  514 bytes       5  [emitted]  app
static/css/app.05222d776249e64862bd4957a923bd69.css.map    1.02 kB          [emitted]
                static/js/0.db4a749397b58d06ec83.js.map    18.1 kB       0  [emitted]
                static/js/1.a3e3b4daaa5b3ce912a9.js.map     3.8 kB       1  [emitted]
                static/js/2.1120d25dace1a3c02081.js.map    3.65 kB       2  [emitted]
                static/js/3.395f900be5a61e751d87.js.map    3.76 kB       3  [emitted]
           static/js/vendor.bbddf67a6696c765f88f.js.map     473 kB       4  [emitted]  vendor
              static/js/app.9e45a1d5c470dbc4056b.js.map    7.15 kB       5  [emitted]  app
         static/js/manifest.93a29dadc6f6f8fc031c.js.map     7.9 kB       6  [emitted]  manifest
                                             index.html  515 bytes          [emitted]

  Build complete.

四个组件, 都是用了懒加载方式, 所有生成了额外的4个js文件

《vue-route基本使用》

嵌套路由

  • 嵌套路由是一个很常见的功能
    • 比如在home页面中, 我们希望通过/home/news和/home/message访问一些内容.
    • 一个路径映射一个组件, 访问这两个路径也会分别渲染两个组件.
  • 实现嵌套路由有两个步骤:
    • 创建对应的子组件, 并且在路由映射中配置对应的子路由.
    • 在组件内部使用标签.

src/components/Home.vue

<template>
<div>
  <h2>我是Home组件</h2>
  <p>我是Home组件的内容</p>
  <!--渲染出两个A标签,然后对应到嵌套路由(子路由)-->
  <router-link to="/home/news">新闻</router-link>
  <router-link to="/home/message">消息</router-link>
  <!--对应组件展示预留的位置-->
  <router-view></router-view>
</div>
</template>

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

<style scoped>
h2 {
  color: red;
}
</style>

src/components/HomeNews.vue

<template>
<div>
  <ul>
    <li>新闻1</li>
    <li>新闻2</li>
    <li>新闻3</li>
  </ul>
</div>
</template>

src/components/HomeMessage.vue

<template>
<div>
  <ul>
    <li>信息1</li>
    <li>信息2</li>
    <li>信息3</li>
    <li>信息4</li>
  </ul>
</div>
</template>

src/router/index.js

import Vue from 'vue'
import Router from 'vue-router'
// import HelloWorld from '@/components/HelloWorld'
// import Home from '../components/Home'
// import About from '../components/About'
// import User from "../components/User";

// 1. 通过Vue.use安装插件
Vue.use(Router)

// 在这里导入, 然后在下面引用, 或者在下面component中直接引用也可以
const About = () => import('../components/About')
const User = () => import('../components/User')
const Home = () => import('../components/Home')
const HomeNews = () => import('../components/HomeNews')
const HomeMessage = () => import('../components/HomeMessage')


// 2. 将下面的router拆除出来,单独创建VueRoute对象
const routes= [
  {
    path: '/',
    redirect: '/helloWorld'
  },
  {
    path: '/helloWorld',
    component: () => import('../components/HelloWorld')
  },
  {
    path: '/home',
    component: Home,
    // 创建子路由
    children: [
      {
        path: "",
        component: HomeNews
      },
      {
        // 子路由中不需要写/ 会和父路由进行拼接
        path: "news",
        component: HomeNews
      },
      {
        path: "message",
        component: HomeMessage
      }
    ]
  },
  {
    path: '/about',
    component: About
  },
  {
    path: '/user/:userId',
    component: User
  }
]

// 3. 创建VueRoute对象,并导出,然后在vue实例中挂载
export default new Router({
  // 配置路径和组件的应用关系
  routes,
  mode: "history",
  linkActiveClass: "active"
})

《vue-route基本使用》

《vue-route基本使用》

《vue-route基本使用》

《vue-route基本使用》

路由报错

路由冗余重复报错

import Vue from 'vue'
import Router from 'vue-router'


// 解决用一个路由重复点击报错问题
// NavigationDuplicated: Avoided redundant navigation to current location
// 获取原型对象上的push函数
const originalPush = Router.prototype.push
// 修改原型对象中的push方法
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(Router)
点赞

发表评论

邮箱地址不会被公开。

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据