Vue Router 与 Pinia
2026/11/25大约 2 分钟
Vue Router 与 Pinia
一、Vue Router 基本配置
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/',
component: () => import('../layouts/AppLayout.vue'),
children: [
{ path: '', name: 'home', component: () => import('../pages/Home.vue') },
{ path: 'users/:id', name: 'user', component: () => import('../pages/UserDetail.vue') },
{ path: ':pathMatch(.*)*', name: 'not-found', component: () => import('../pages/NotFound.vue') }
]
}
]
})要点:
createWebHistory使用 HTML5 History,需要服务端配置回退到index.html。- 路由组件懒加载,按页面拆分包。
- 动态参数通过
route.params.id读取,注意类型与存在性校验。 meta可存放权限、标题、布局等路由元信息。
二、嵌套路由与导航守卫
- 嵌套路由用
children,父组件通过<RouterView />渲染子路由。 - 全局守卫:
router.beforeEach、router.afterEach。 - 路由独享守卫:
beforeEnter。 - 组件内守卫:
onBeforeRouteLeave、onBeforeRouteUpdate。
router.beforeEach((to) => {
const auth = useAuthStore()
if (to.meta.requiresAuth && !auth.isLogin) {
return { name: 'login', query: { redirect: to.fullPath } }
}
})注意:
- 守卫中避免无限重定向,放行时返回
true或undefined。 - 异步权限校验要处理失败与超时。
- 路由切换后旧请求应取消,避免覆盖新页面数据。
三、Pinia 基本用法
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
getters: {
double: (state) => state.count * 2
},
actions: {
increment() {
this.count += 1
}
}
})组合式写法:
export const useUserStore = defineStore('user', () => {
const user = ref<User | null>(null)
const isLogin = computed(() => !!user.value)
async function fetchUser() {
user.value = await api.getUser()
}
return { user, isLogin, fetchUser }
})要点:
storeToRefs用于解构 state/getters,保持响应性;actions 可以直接解构。- getters 只做派生计算,不写副作用。
- actions 可以包含异步逻辑。
- 跨 store 调用时注意循环依赖。
四、持久化
- 简单场景可用
pinia-plugin-persistedstate。 - 只持久化必要字段,避免把敏感信息写入
localStorage。 - 持久化数据结构变化时要设计版本号与迁移逻辑。
- 多标签页同步可用
storage事件或 BroadcastChannel。
五、Vuex 迁移提示
Vuex 是 Vue 2 时代的主流方案,Vue 3 新项目优先 Pinia。
state→ Piniastategetters→ Piniagettersmutations+actions→ Piniaactionsmodules→ 多个独立 storecommit/dispatch→ 直接调用 action
迁移时先保持业务行为不变,再逐步拆分 store,避免一次性重写。
六、常见易错点
- 路由守卫中未处理异步失败,页面卡死。
- 动态路由参数变化后组件复用,但没有重新请求数据。
- 直接解构 store 导致响应性丢失,忘记
storeToRefs。 - 把所有状态放进一个巨大 store,职责不清。
- 持久化了 token 等敏感信息,带来安全风险。
- 服务端状态与客户端状态混在一起,缓存失效难以控制。
