1.可以devDependencies安装:npm install vue-router -D
2.创建路由文件src/router/index.js或者src/router.js:
import Vue from "vue"; import Router from "vue-router"; //路由细分模块 import travel from "./modules/travel"; import goods from "./modules/goods"; //组件模块 import defaultPage from "./../components/404"; Vue.use(Router); export default new Router({ mode: "history", base: "/guojing", routes: [ ...travel, ...goods, { path: "*", redirect: "/404", name: "*" }, { path: "/404", name: "404", component: defaultPage, meta: { title: "页面未找到" }, }, ], });
引入并使用router,实例化一个Router对象并抛出,上面是一个例子。
3.引入到src/main.js,并注入到Vue实例:
import Vue from 'vue' import App from './App.vue' import router from './router' import 'amfe-flexible/index'//设置font-size为 deviceWidth / 10,配合postcss-adaptive-exclude使用 Vue.config.productionTip = false new Vue({ router, render: h => h(App), }).$mount('#app')
4.入口App.vue中使用:
<template> <div id="app"> <keep-alive :exclude="exclude_pages"> <router-view /> </keep-alive> </div> </template> <script> export default { name: 'app', data(){ return{ exclude_pages: ['TravelIndex'], } } } </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; } </style>
路由有两种模式,上面采用的是history模式,也是最常用的模式。