一步一步建立你本身的Vue路由器

建立一個基本路由器組件

咱們首先建立用於路由的兩個頁面Home.vue和List.vue用於路由的兩個頁面vue

Home.vue
<template>
  <div>home</div>
</template>

List.vue
<template>
  <div>list</div>
</template>

定義路由和渲染路由

咱們先來建立一個AppRouter.vue文件,它將成爲路由器組件自己,並具備路由的定義app

<template>
  <component :is="routedComponent"></component>
</template>

<script>
import Home from "./Home.vue";
import List from "./List.vue";
const routes = {
  "/": Home,
  "/list": List
};
export default {
  data() {
    return {
      current: window.location.pathname
    };
  },
  computed: {
    routedComponent() {
      return routes[this.current];
    }
  }
};
</script>

這裏咱們採用component 來動態渲染不一樣的路由組件this

使用路由

咱們看下app配置路由的使用code

<template>
  <div>
    <button @click="goto('/')">go TO home</button>
    <button @click="goto('/list')">go TO List</button>
    <app-router></app-router>
  </div>
</template>

<script>
import AppRouter from "./components/AppRouter";

export default {
  components: {
    AppRouter
  },
  methods: {
    goto(router) {
      window.location.pathname = router;
    }
  }
};
</script>

一個簡單的路由組器就實現了。component

https://codesandbox.io/s/jjv1...
上述demo在這裏能夠看到。router

上述路由還有點小問題,就是會刷新頁面,下一篇來探討下怎麼樣實現不刷新頁面的路由器。ip

謝謝路由