咱们首先建立用于路由的两个页面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
谢谢路由