这里说的路由指用在单页应用(single-page-application)的路由,既达到动态修改页面且不刷新
原理一般是用hash 或者 history.pushState来实现

1 简单实现(利用history.pushState)

参考vue官方简单实现

  1. // 入口文件
  2. import Vue from 'vue'
  3. import routes from './routes'
  4. const app = new Vue({
  5. el: '#app',
  6. data: {
  7. currentRoute: window.location.pathname
  8. },
  9. computed: {
  10. ViewComponent () {
  11. const matchingView = routes[this.currentRoute]
  12. return matchingView
  13. ? require('./pages/' + matchingView + '.vue')
  14. : require('./pages/404.vue')
  15. }
  16. },
  17. render (h) {
  18. return h(this.ViewComponent)
  19. }
  20. })
  21. //监听 浏览器操作(点击前进和后退按钮)或者调用js(go、back)
  22. // 但是调用pushState、replaceState并不会触发popstate事件
  23. window.addEventListener('popstate', () => {
  24. app.currentRoute = window.location.pathname
  25. })
  1. // 跳转组件
  2. <template>
  3. <a
  4. v-bind:href="href"
  5. v-bind:class="{ active: isActive }"
  6. v-on:click="go"
  7. >
  8. <slot></slot>
  9. </a>
  10. </template>
  11. <script>
  12. import routes from '../routes'
  13. export default {
  14. props: {
  15. href: {
  16. type:String,
  17. required: true
  18. }
  19. },
  20. computed: {
  21. isActive () {
  22. return this.href === this.$root.currentRoute
  23. }
  24. },
  25. methods: {
  26. go (event) {
  27. event.preventDefault()
  28. // 修改根实例,达到动态匹配
  29. this.$root.currentRoute = this.href
  30. // 利用histroy.pushState达到修改浏览器url且不会发请求刷新
  31. window.history.pushState(
  32. null,
  33. routes[this.href],
  34. this.href
  35. )
  36. }
  37. }
  38. }
  39. </script>
  40. <style scoped>
  41. .active {
  42. color: cornflowerblue;
  43. }
  44. </style>