官方文档给的东西还是不够详细,这里给出自己开发中遇到的实例供大家参考。
首先当然是安装
这里只给出 npm 方式安装
npm install vue-router
如果在一个模块化工程中使用它,必须要通过 Vue.use()
明确地安装路由功能:
1.找到文件的入口 js 文件,通常是 src 目录下的 main.js
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
2.定义 (路由) 组件。
可以从其他文件 import 进来
import goods from './components/goods/goods';
import ratings from './components/ratings/ratings';
import seller from './components/seller/seller';
3.定义路由
每个路由应该映射一个组件。 其中"component" 可以是通过 Vue.extend() 创建的组件构造器, 或者,只是一个组件配置对象。
const routes = [
{path: '/goods', component: goods},
{path: '/ratings', component: ratings},
{path: '/seller', component: seller}
];
4.创建 router 实例,然后传 `routes` 配置
const router = new VueRouter({
linkActiveClass: 'active',
routes: routes //也可以直接简写成 routes
});
5.创建和挂载根实例。
记得要通过 router 配置参数注入路由, 从而让整个应用都有路由功能
/* eslint-disable no-new */
new Vue({
router,
el: '#app',
render: h => h(App)
});
上面第一句注释不能少,这是让 eslint 检测器忽略其语法检测
最后如果你需要默认地址进入哪个路由可以加上最后一句
router.push('/goods');
这样一个简单的路由功能就配置好了!