vue-router

236 阅读1分钟

1. 安装

npm install vue-router

2. 模块化使用

在router文件加index.js中:

import Vue from 'vue';
import Router from 'vue-router';
import appMian from '@/components/appMain';
Vue.use(Router);
export default new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'appMian',
      component: appMian,
    }
  ],
});

main.js中导入router

import router from './router';
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>',
});

3. 配置路由出口

App.vue:

    <!-- 路由出口 -->
    <!-- 路由匹配到的组件将渲染在这里 -->
    <router-view />

4. 路由的三种方法

第一种:
  <router-link :to="{ name: 'copy' }"
    ><el-button type="success" plain>Go to copy</el-button></router-link
  >
第二种:
  <router-link to="/drag"
    ><el-button type="success" plain>Go to drag</el-button></router-link
  >
第三种:
  <div @click="tabComponent">
    <el-button type="success" plain>Go to tabComponent</el-button>
  </div>
tabComponent() {
 this.$router.push("/tabComponent");
}

<router-link> 默认会被渲染成一个 <a> 标签

消除router-link下滑线

a {
  text-decoration: none;
  color: #67c23a;
}
.router-link-active {
  text-decoration: none;
  color: #67c23a;
}

5. 重定向

从 /a 重定向到 /b:

const router = new VueRouter({
  routes: [
    { path: '/a', redirect: '/b' },
    { path: '/bar', redirect: { name: 'foo' } },
    {
      path: '/a', redirect: to => {
        // 方法接收 目标路由 作为参数
        // return 重定向的 字符串路径/路径对象
      }
    }
  ]
})

6. 别名

/a 的别名是 /b,意味着,当用户访问 /b 时,URL 会保持为 /b,但是路由匹配则为 /a,就像用户访问 /a 一样。

const router = new VueRouter({
  routes: [
    { path: '/a', component: A, alias: '/b' }
  ]
})

7. 路由的其他方法

  1. router.push()
  2. router.replace(location, onComplete?, onAbort?) ---:它不会向 history 添加新记录,而是跟它的方法名一样 —— 替换掉当前的 history 记录。
  3. router.replace(location, onComplete?, onAbort?)
声明式 编程式
<router-link :to="..." replace> router.replace(...)
  1. router.go(n) --->这个方法的参数是一个整数,意思是在 history 记录中向前或者后退多少步,类似window.history.go(n)

这几个方法是效仿window.history方法的