【vue-router】01 - 安装与基本使用

55 阅读1分钟

1. 安装

npm i vue-router

2. 新建路由信息表

/src/router/index.ts

import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'

const routes: Array<RouteRecordRaw> = [
    { 
        path: '/',
        component: () => import('../pages/Login.vue')
    },
    {
        path: '/reg',
        component: () => import('../pages/Reg.vue')
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes: routes
})

export default router

3. 新建路由组件

/src/pages/Login.vue

<template>
<div class="login">Login</div>
</template>

<style scoped>
.login {
    width: 400px;
    height: 400px;
    background-color: red;
    color: white;
    font-size: 30px;
}
</style>

/src/pages/Reg.vue

<template>
<div class="register">Register</div>
</template>

<style scoped>
.register {
    width: 400px;
    height: 400px;
    background-color: green;
    color: white;
    font-size: 30px;
}
</style>

4. 注册路由信息表

/src/main.ts

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

const app = createApp(App)

// 注册路由
app.use(router)

app.mount('#app')

5. 使用路由

/src/App.vue

<template>
    <!-- 路由跳转标签,本质上是 a 标签 -->
    <router-link to="/">login</router-link>
    <router-link to="/register" style="margin-left: 20px;">register</router-link>
    
    <!-- 需要给路由组件占个位 -->
    <router-view></router-view>
</template>

6. 路由模式

6.1 hash

const router = createRouter({
    history: createWebHashHistory(),
    routes: routes
})

hash 是 URL 中 hash(#) 及后面的那部分,常用作锚点在页面内进行导航,改变 URL 中的 hash 部分不会引起页面刷新

通过 hashchange 事件监听 URL 的变化,改变 URL 的方式只有这几种:

1. 通过浏览器前进后退改变 URL
2. 通过 <a> 标签改变 URL
3. 通过 window.location 改变 URL
window.addEventListener('hashchange', (e) => { console.log(e) })

6.2 history

const router = createRouter({
    history: createWebHistory(),
    routes: routes
})

history 提供了 pushState 和 replaceState 两个方法,这两个方法改变 URL 的 path 部分不会引起页面刷新

history 提供类似 hashchange 事件的 popstate 事件,但 popstate 事件有些不同:

1. 通过浏览器前进后退改变 URL 时会触发 popstate 事件
2. 通过 js 调用 history 的 back,go,forward 方法可触发该事件
3. 通过 pushState/replaceState 或 <a> 标签改变 URL 不会触发 popstate 事件,
    但好在我们可以拦截 pushState/replace 的调用和 <a> 标签的点击事件来检测 URL 变化
    

所以监听 URL 变化可以实现,只是没有 hashchange 那么方便

// 路由的跳转 pushState or replaceState or <a>
// pushState
// param1: 传递的数据,param2: title,param3: 路径
history.pushState({state: 1}, "", "/path")