Vue-Router 学习

127 阅读1分钟

Vue2 使用

npm install vue-router@3.x.x  // 安装插件
yarn add vue-router@3.x.x  // 安装指定版本插件

创建 router/index.js 文件

import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

const VueRouterTest = () => import('@/views/router-test');

const routes = [
    { path: '/foo', component: VueRouterTest },
    // path  路径
    // component  组件
];

const router = new VueRouter({
    routes // (缩写) 相当于 routes: routes
})

export default router;

main.js 加载

new Vue({
    router,
     render: h => h(App),
}).$mount('#app');

Vue3 使用

npm install vue-router@4
yarn add vue-router@4

router/index.js 不变

main.js 加载

const app = Vue.createApp(App)
app.use(router)
app.mount('#app')

路由对象属性

  1. path // 字符串,对应当前路由的路径,总是为组件的绝对路径
  2. params // 对象,如果没有路由参数,就是一个空对象
  3. query // xxx/xx?user=1 ?之后 表示 URL 查询参数,如果没有查询参数,则是个空对象
  4. name // 当前路由的名称,如果有的话
  5. redirectedFrom // 重定向 使用 { path: '/a', redirect: '/b' }

官方API使用

官方API