Vue Router
是 Vue.js
官方的路由管理器。它和 Vue.js
的核心深度集成,让构建单页面应用变得易如反掌。包含的功能有:css
Vue.js
过渡系统的视图过渡效果CSS class
的连接HTML5
历史模式或 hash
模式,在 IE9
中自动降级安装命令html
npm install vue-router --save
若是在一个模块化工程中使用它,必需要经过 Vue.use()
明确地安装路由功能:vue
import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter)
模块化使用
以前咱们使用脚手架vue-cli
建立项目时,实际已经配置好了router
,建立完项目后,在项目根目录下会有一个router
文件夹,router
下有一个index.js
文件,内容以下:vue-router
import Vue from "vue"; import VueRouter from "vue-router"; import Home from "../views/Home.vue"; // 1. 当咱们使用其余插件的时候,就必须使用Vue.use安装插件 Vue.use(VueRouter); // 2. 定义路由,每一个路由应该映射一个组件 const routes = [ { path: "/", name: "Home", component: Home, }, { path: "/about", name: "About", component: About }, ]; // 3. 建立router实例 const router = new VueRouter({ // 配置路由和组件之间的应用关系 routes, // (缩写) 至关于 routes: routes }); // 4. 导出router对象,而后在main.js中引用 export default router;
这个文件是专门配置路由的,最后将router
对象导出后,咱们在项目的main.js
中引用便可vue-cli
import Vue from "vue"; import App from "./App.vue"; import router from "./router"; Vue.config.productionTip = false; new Vue({ router, // 在vue实例中添加router对象,就可使用路由了 render: (h) => h(App), }).$mount("#app");
咱们的2个组件代码About
和Home
代码以下:npm
// About.vue <template> <div class="about"> <h1>About</h1> </div> </template> <script> export default { name: "About" } </script> <style scoped> </style> // Home.vue <template> <div class="home"> <h1>Home</h1> </div> </template> <script> export default { name: "Home", }; </script> <style scoped> </style>
最后咱们在App.vue
中,写入以下代码:浏览器
<template> <div id="app"> <router-link to="/">首页</router-link> <router-link to="/about">关于</router-link> <router-view></router-view> </div> </template> <style lang="scss"> </style>
使用<router-link>
来加载连接,而后使用to
表示跳转的连接。最终会把<router-link>
渲染成<a>
标签。<router-view>
是路由的出口,也就是相应url
下的代码会被渲染到这个地方来。
app
可是当咱们启动程序,访问页面的时候,url
地址上会出现#
这是由于vue-router
默认 hash
模式 —— 使用 URL
的 hash
来模拟一个完整的 URL
,因而当 URL
改变时,页面不会从新加载。
若是不想要很丑的 hash
,咱们能够用路由的 history
模式,这种模式充分利用 history.pushState API
来完成 URL
跳转而无须从新加载页面。ide
const router = new VueRouter({ mode: 'history', routes: [...] })
咱们只需在router
文件夹下的index.js
中添加mode
为history
便可,以后从新访问,http://localhost:8080/
就不会有#
号了模块化
注意:history
模式还须要后台配置支持。由于咱们的应用是个单页客户端应用,若是后台没有正确的配置,当用户在浏览器直接访问其余url
地址就会返回 404,这就很差看了。
因此呢,你要在服务端增长一个覆盖全部状况的候选资源:若是 URL
匹配不到任何静态资源,则应该返回同一个 index.html
页面,这个页面就是你 app
依赖的页面。