**使用步骤**
1.创建router对象,router/index.js
import Vue from 'vue'//路由组件
import VueRouter from '../vuerouter'
import Home from '../views/Home.vue'
//注册插件
//Vue.use()内部调用传入对象的install方法
Vue.use(VueRouter)
//路由规则
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
}
]
//路由对象
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
2.注册router对象,main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
Vue.config.productionTip = false
//创建vue实例,注册router对象
new Vue({
router,
render: h => h(App)
}).$mount('#app')
3.创建路由组建的占位,创建链接,App.vue
<template>
<div id="app">
<div id="nav">
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
</div>
<router-view/>
</div>
</template>
4.创建文件,vuerouter/index.js
代码实现
export default class VueRouter { }
-
静态方法install
let _Vue = null export default class VueRouter { //Vue:vue的构造函数 static install (Vue) { //1.判断插件是否已经被加载 if (VueRouter.install.installed) { return } VueRouter.install.installed = true //2.把Vue构造函数记录到全局变量 _Vue = Vue //3.当Vue加载的时候把传入的router对象挂载到Vue实例上(注意:只执行一次) //混入 _Vue.mixin({ beforeCreate () { //判断router对象是否已经挂载在了Vue实例上 if (this.$options.router) { //把router对象注入到Vue实例上 _Vue.prototype.$router = this.$options.router } } }) } -
构造函数
//构造函数
constructor (options) { this.options = options //记录路径和对应的组件 this.routeMap = {} this.data = _Vue.observable({ //当前的默认路径 current:'/' }) } -
createRouteMap ()方法
createRouteMap () {
//遍历所有的路由规则,把路由规则解析成键值对的形式存储到routerMap中 this.options.routes.forEach( route => { this.routeMap[route.path] = route.component }) } -
initComponents ()
initComponents (Vue) {
Vue.component('router-link', { props: { to:String }, // 需要带编译器版本的Vue.js //template: '<a :href="to"><slot></slot></a>' //使用运行时版本的vue.js render (h) { return h('a', { attrs:{ href: this.to }, on: { click:this.clickHandler } },[this.$slots.default]) }, methods:{ clickHandler(e) { history.pushState({},'',this.to) this.$router.data.current = this.to e.preventDefault() } } }) const self = this Vue.component('router-view', { render (h) { const component = self.routeMap[self.data.current] return h(component) } }) } -
initEvents ()
initEvents () {
window.addEventListener('popstate', () => {
this.data.current = window.location.pathname
}) }
-
init()
init () {
this.createRouteMap() this.initComponents(_Vue) this.initEvents() }//在install方法中添加
if (this.$options.router) {
//把router对象注入到Vue实例上 _Vue.prototype.$router = this.$options.router this.$options.router.init() } -
vue-cli创建项目默认使用的是运行时版本的vue.js
-
如果想换成带编译器版本的vue.js,需要修改vue-cli配置
-
在项目根目录下创建vue.config.js文件
module.exports = { runtimeCompiler:true }