这里说的路由指用在单页应用(single-page-application)的路由,既达到动态修改页面且不刷新
原理一般是用hash 或者 history.pushState来实现
1 简单实现(利用history.pushState)
// 入口文件
import Vue from 'vue'
import routes from './routes'
const app = new Vue({
el: '#app',
data: {
currentRoute: window.location.pathname
},
computed: {
ViewComponent () {
const matchingView = routes[this.currentRoute]
return matchingView
? require('./pages/' + matchingView + '.vue')
: require('./pages/404.vue')
}
},
render (h) {
return h(this.ViewComponent)
}
})
//监听 浏览器操作(点击前进和后退按钮)或者调用js(go、back)
// 但是调用pushState、replaceState并不会触发popstate事件
window.addEventListener('popstate', () => {
app.currentRoute = window.location.pathname
})
// 跳转组件
<template>
<a
v-bind:href="href"
v-bind:class="{ active: isActive }"
v-on:click="go"
>
<slot></slot>
</a>
</template>
<script>
import routes from '../routes'
export default {
props: {
href: {
type:String,
required: true
}
},
computed: {
isActive () {
return this.href === this.$root.currentRoute
}
},
methods: {
go (event) {
event.preventDefault()
// 修改根实例,达到动态匹配
this.$root.currentRoute = this.href
// 利用histroy.pushState达到修改浏览器url且不会发请求刷新
window.history.pushState(
null,
routes[this.href],
this.href
)
}
}
}
</script>
<style scoped>
.active {
color: cornflowerblue;
}
</style>