简单使用

完整代码:https://codesandbox.io/s/elastic-dust-0hwun

  1. import Vue from "vue";
  2. // 1. 引入vue-router
  3. import Router from "vue-router";
  4. import HelloWorld from "../components/HelloWorld";
  5. import A from "../components/A";
  6. // 2. 注册成vue插件
  7. Vue.use(Router);
  8. // 3. 新建router实例,传递配置信息
  9. export default new Router({
  10. routes: [
  11. {
  12. path: "/hello",
  13. component: HelloWorld
  14. },
  15. {
  16. path: "/a",
  17. component: A
  18. }
  19. ]
  20. });
  1. import Vue from "vue";
  2. import App from "./App.vue";
  3. import router from "./router";
  4. Vue.config.productionTip = false;
  5. new Vue({
  6. render: (h) => h(App),
  7. router // 将router实例注入到vue根组件实例
  8. }).$mount("#app");

使用router-link指定跳转的path,在router-view中显示内容

  1. <template>
  2. <div id="app">
  3. <!-- router-link跳转 -->
  4. <router-link to="/hello">Hello</router-link> |
  5. <router-link to="/A">aaa</router-link>
  6. <!-- router-view显示组件内容 -->
  7. <router-view />
  8. </div>
  9. </template>

我们可以使用this.$router 访问路由器,$router包含push,go,forward,back等方法
也可以通过 this.$route 访问当前路由

一条route里有多个组件

使用components对象

  1. export default new Router({
  2. routes: [
  3. {
  4. path: "/hello",
  5. component: HelloWorld
  6. },
  7. {
  8. path: "/ab",
  9. components: {
  10. main: A,
  11. side: B
  12. }
  13. }
  14. ]
  15. });

router-view指定name

  1. <template>
  2. <div id="app">
  3. <router-link to="hello">hello</router-link> |
  4. <router-link to="ab">ab</router-link>
  5. <router-view />
  6. <router-view name="main" />
  7. <router-view name="side" />
  8. </div>
  9. </template>

完整代码:https://codesandbox.io/s/damp-pine-rpxf8

传递参数

1.每条route必须添加name
2.path后加 /:xxx

  1. export default new Router({
  2. routes: [
  3. {
  4. name: "hello",
  5. path: "/hello/:msg",
  6. component: HelloWorld
  7. },
  8. {
  9. name: "aaa",
  10. path: "/a/:msg&author=:name",
  11. component: A
  12. }
  13. ]
  14. });

3.router-link传入包含name和params的对象

  1. <template>
  2. <div id="app">
  3. <!-- router-link跳转 -->
  4. <router-link :to="{ name: 'hello', params: { msg: '我是hello world' } }"
  5. >Hello</router-link
  6. >
  7. |
  8. <router-link :to="{ name: 'aaa', params: { msg: '我是aaa', name: '小王' } }"
  9. >aaa</router-link
  10. >
  11. <!-- router-view显示组件内容 -->
  12. <router-view />
  13. </div>
  14. </template>

4.各组件可以通过this.$route.params获取传递的参数
完整代码:https://codesandbox.io/s/jolly-lamarr-6jf9y

路由重定向

用redirect实现重定向

  1. const routes: Array<RouteConfig> = [
  2. {
  3. path: '/',
  4. redirect: '/money'
  5. }
  6. ]