vue router: 路由

169 阅读1分钟

vue2

下载路由

npm install vue-router@3.x.x -D

使用版本为v3.x的,不然语法会报错,总之一句话,什么版本的包对应什么版本的语法!

标签

// to 对应 routes 设置的路径(path)
// tag 是表示你想渲染成的标签的名字,默认是 <a> 标签
<router-link to="" tag=""></router-link>

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

路由配置

routes文件

const routes = [
    {
        name: 'a',
        path: '/',
        // 用来做路由面包屑
        meta: {}
        component: () => import('@/components/a.vue')
    }
]

export default routes

router.js文件

import Vue from 'vue';
import Router from 'vue-router';
import routes from './routes.js'

Vue.use(Router);
const router = new Router({
    routes,
    mode: 'hash' // 'history'
})

export default router;

main.js

import router from '../router/router.js';

const app = new Vue({
    router
}).$mount('#app')

路由获取方法

this.$route  || this.$router

this.$route: 当前路由
this.$router: 路由器