最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Vue3項(xiàng)目中多頁面路由配置與Pinia狀態(tài)管理的完全指南

 更新時(shí)間:2026年04月17日 08:57:02   作者:梵得兒SHI  
本文詳細(xì)介紹了Vue3多頁面應(yīng)用開發(fā)中VueRouter4的配置和使用方法,包括首頁、列表頁、詳情頁的頁面導(dǎo)航與參數(shù)傳遞,并展示了Pinia狀態(tài)管理與用戶登錄狀態(tài)、用戶信息管理的實(shí)現(xiàn)方法,需要的朋友可以參考下

在 Vue 3 項(xiàng)目開發(fā)中,多頁面路由是構(gòu)建單頁應(yīng)用(SPA)的核心骨架,而 Pinia 狀態(tài)管理則是解決組件間數(shù)據(jù)共享的利器。本文將從實(shí)戰(zhàn)角度出發(fā),一步步帶你配置首頁、列表頁、詳情頁的路由,實(shí)現(xiàn)頁面導(dǎo)航與參數(shù)傳遞,并結(jié)合 Pinia 管理用戶登錄狀態(tài)、用戶信息,同時(shí)實(shí)現(xiàn)狀態(tài)持久化,配合清晰的圖解,讓你輕松掌握 Vue 3 開發(fā)的核心技能。

一、開發(fā)多頁面應(yīng)用:Vue Router 4 實(shí)戰(zhàn)

Vue Router 4 是 Vue 3 的官方路由管理器,通過它我們可以輕松實(shí)現(xiàn)頁面間的切換、參數(shù)傳遞等功能。

1.1 安裝與基礎(chǔ)配置

首先,在 Vue 3 項(xiàng)目中安裝 Vue Router 4:

npm install vue-router@4

接下來,創(chuàng)建路由配置文件 src/router/index.js

import { createRouter, createWebHistory } from 'vue-router'
// 引入頁面組件
import Home from '@/views/Home.vue'
import List from '@/views/List.vue'
import Detail from '@/views/Detail.vue'
// 定義路由規(guī)則
const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home // 首頁
  },
  {
    path: '/list',
    name: 'List',
    component: List // 列表頁
  },
  {
    path: '/detail/:id', // 動(dòng)態(tài)路由,:id 為參數(shù)占位符
    name: 'Detail',
    component: Detail // 詳情頁
  }
]
// 創(chuàng)建路由實(shí)例
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL), // 使用 HTML5 History 模式
  routes
})
export default router

然后在 main.js 中注冊路由:

import { createApp } from 'vue'
import App from './App.vue'
import router from './router' // 引入路由配置
const app = createApp(App)
app.use(router) // 注冊路由
app.mount('#app')

最后,在 App.vue 中添加路由出口 <router-view>

<template>
  <div id="app">
    <!-- 路由出口,匹配到的頁面組件會(huì)渲染在這里 -->
    <router-view></router-view>
  </div>
</template>

1.2 配置首頁、列表頁、詳情頁組件

我們先創(chuàng)建三個(gè)基礎(chǔ)頁面組件:

1.2.1 首頁 (src/views/Home.vue)

<template>
  <div class="home">
    <h1>首頁</h1>
    <p>歡迎來到 Vue 3 多頁面應(yīng)用!</p>
    <!-- 使用 router-link 進(jìn)行聲明式導(dǎo)航 -->
    <router-link to="/list">跳轉(zhuǎn)到列表頁</router-link>
  </div>
</template>
<style scoped>
.home { padding: 20px; }
</style>

1.2.2 列表頁 (src/views/List.vue)

<template>
  <div class="list">
    <h1>列表頁</h1>
    <ul>
      <!-- 模擬列表數(shù)據(jù) -->
      <li v-for="item in list" :key="item.id">
        <!-- 跳轉(zhuǎn)到詳情頁,傳遞 id 參數(shù) -->
        <router-link :to="`/detail/${item.id}`">{{ item.title }}</router-link>
      </li>
    </ul>
    <router-link to="/">返回首頁</router-link>
  </div>
</template>
<script setup>
import { ref } from 'vue'
// 模擬列表數(shù)據(jù)
const list = ref([
  { id: 1, title: '文章一:Vue Router 入門' },
  { id: 2, title: '文章二:Pinia 狀態(tài)管理' },
  { id: 3, title: '文章三:Vue 3 組合式 API' }
])
</script>
<style scoped>
.list { padding: 20px; }
li { margin: 10px 0; }
</style>

1.2.3 詳情頁 (src/views/Detail.vue)

<template>
  <div class="detail">
    <h1>詳情頁</h1>
    <p>當(dāng)前文章 ID:{{ articleId }}</p>
    <p>文章標(biāo)題:{{ articleTitle }}</p>
    <!-- 編程式導(dǎo)航返回列表頁 -->
    <button @click="goBack">返回列表頁</button>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router' // 引入路由鉤子
const route = useRoute() // 獲取當(dāng)前路由信息
const router = useRouter() // 獲取路由實(shí)例,用于編程式導(dǎo)航
const articleId = ref('')
const articleTitle = ref('')
// 模擬文章數(shù)據(jù)
const articles = {
  1: '文章一:Vue Router 入門',
  2: '文章二:Pinia 狀態(tài)管理',
  3: '文章三:Vue 3 組合式 API'
}
onMounted(() => {
  // 接收動(dòng)態(tài)路由參數(shù) :id
  articleId.value = route.params.id
  articleTitle.value = articles[articleId.value] || '文章不存在'
})
// 編程式導(dǎo)航返回列表頁
const goBack = () => {
  router.push('/list')
}
</script>
<style scoped>
.detail { padding: 20px; }
</style>

1.3 頁面導(dǎo)航與參數(shù)傳遞詳解

1.3.1 兩種導(dǎo)航方式

  • 聲明式導(dǎo)航:使用 <router-link> 組件,通過 to 屬性指定目標(biāo)路徑,適合在模板中直接使用。
  • 編程式導(dǎo)航:使用 useRouter 鉤子獲取路由實(shí)例,調(diào)用 router.push()router.replace() 等方法,適合在邏輯代碼中使用。

1.3.2 兩種參數(shù)傳遞方式

表格

方式寫法接收方式刷新頁面示例
動(dòng)態(tài)路由參數(shù)path: '/detail/:id',跳轉(zhuǎn):/detail/1route.params.id參數(shù)保留詳情頁 ID
Query 參數(shù)跳轉(zhuǎn):/detail?id=1route.query.id參數(shù)保留搜索關(guān)鍵詞

注意:如果使用 name 配合 params 跳轉(zhuǎn)(如 router.push({ name: 'Detail', params: { id: 1 } })),刷新頁面后參數(shù)會(huì)丟失,建議優(yōu)先使用動(dòng)態(tài)路由參數(shù)或 Query 參數(shù)。

1.4 路由導(dǎo)航流程圖解

二、Pinia 狀態(tài)管理:用戶登錄與持久化

Pinia 是 Vue 3 的官方狀態(tài)管理庫,相比 Vuex 更簡潔、更符合組合式 API 的設(shè)計(jì)理念,支持 TypeScript,且 DevTools 支持更好。

2.1 Pinia 安裝與注冊

首先安裝 Pinia 和持久化插件(用于狀態(tài)刷新不丟失):

npm install pinia
npm install pinia-plugin-persistedstate

然后在 main.js 中注冊 Pinia 和持久化插件:

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import { createPinia } from 'pinia' // 引入 Pinia
import piniaPersistedstate from 'pinia-plugin-persistedstate' // 引入持久化插件
const app = createApp(App)
const pinia = createPinia() // 創(chuàng)建 Pinia 實(shí)例
pinia.use(piniaPersistedstate) // 注冊持久化插件
app.use(router)
app.use(pinia) // 注冊 Pinia
app.mount('#app')

2.2 創(chuàng)建 User Store(用戶狀態(tài)管理)

創(chuàng)建 src/store/user.js,用于管理登錄狀態(tài)和用戶信息:

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

// 定義 User Store
export const useUserStore = defineStore('user', () => {
  // 1. State:響應(yīng)式數(shù)據(jù)
  const token = ref('') // 登錄 Token
  const userInfo = ref({}) // 用戶信息

  // 2. Getters:計(jì)算屬性(可選,用于派生狀態(tài))
  const isLoggedIn = computed(() => !!token.value) // 是否登錄

  // 3. Actions:修改狀態(tài)的方法
  // 登錄:保存 Token 和用戶信息
  const login = (newToken, newUserInfo) => {
    token.value = newToken
    userInfo.value = newUserInfo
  }

  // 登出:清空狀態(tài)
  const logout = () => {
    token.value = ''
    userInfo.value = {}
  }

  // 更新用戶信息
  const updateUserInfo = (newInfo) => {
    userInfo.value = { ...userInfo.value, ...newInfo }
  }

  // 返回 state、getters、actions
  return {
    token,
    userInfo,
    isLoggedIn,
    login,
    logout,
    updateUserInfo
  }
}, {
  // 4. 持久化配置
  persist: {
    key: 'user-store', // 存儲(chǔ)在 localStorage 中的 key
    storage: localStorage, // 存儲(chǔ)方式:localStorage 或 sessionStorage
    paths: ['token', 'userInfo'] // 指定需要持久化的 state,默認(rèn)全部
  }
})

2.3 在組件中使用 User Store

我們修改之前的頁面,加入登錄、顯示用戶信息、登出功能:

2.3.1 新增登錄頁 (src/views/Login.vue)

先在路由配置中添加登錄頁路由:

// src/router/index.js
const routes = [
  // ... 之前的路由
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue') // 路由懶加載
  }
]

然后創(chuàng)建登錄頁組件:

<template>
  <div class="login">
    <h1>登錄頁</h1>
    <form @submit.prevent="handleLogin">
      <div>
        <label>用戶名:</label>
        <input v-model="username" placeholder="請輸入用戶名" required />
      </div>
      <div>
        <label>密碼:</label>
        <input v-model="password" type="password" placeholder="請輸入密碼" required />
      </div>
      <button type="submit">登錄</button>
    </form>
  </div>
</template>
<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user' // 引入 User Store
const router = useRouter()
const userStore = useUserStore() // 獲取 Store 實(shí)例
const username = ref('')
const password = ref('')
// 模擬登錄
const handleLogin = () => {
  // 假設(shè)登錄成功,返回 Token 和用戶信息
  const mockToken = 'mock-token-123456'
  const mockUserInfo = {
    id: 1,
    username: username.value,
    avatar: 'https://via.placeholder.com/50'
  }
  // 調(diào)用 Store 的 login 方法
  userStore.login(mockToken, mockUserInfo)
  // 登錄成功后跳轉(zhuǎn)到首頁
  router.push('/')
}
</script>
<style scoped>
.login { padding: 20px; max-width: 300px; margin: 0 auto; }
div { margin: 10px 0; }
input { width: 100%; padding: 8px; box-sizing: border-box; }
button { width: 100%; padding: 10px; background: #42b883; color: white; border: none; cursor: pointer; }
</style>

2.3.2 修改首頁 (src/views/Home.vue),顯示用戶信息

<template>
  <div class="home">
    <h1>首頁</h1>
    <!-- 根據(jù)登錄狀態(tài)顯示不同內(nèi)容 -->
    <div v-if="userStore.isLoggedIn">
      <p>歡迎你,{{ userStore.userInfo.username }}!</p>
      <img :src="userStore.userInfo.avatar" alt="頭像" style="width: 50px; height: 50px; border-radius: 50%;" />
      <button @click="handleLogout">登出</button>
    </div>
    <div v-else>
      <p>你還未登錄,請先登錄。</p>
      <router-link to="/login">去登錄</router-link>
    </div>
    <router-link to="/list">跳轉(zhuǎn)到列表頁</router-link>
  </div>
</template>
<script setup>
import { useUserStore } from '@/store/user'
import { useRouter } from 'vue-router'
const userStore = useUserStore()
const router = useRouter()
// 登出
const handleLogout = () => {
  userStore.logout()
  router.push('/login')
}
</script>
<style scoped>
.home { padding: 20px; }
</style>

2.4 Pinia 狀態(tài)管理流程圖解

三、總結(jié)與最佳實(shí)踐

3.1 路由配置最佳實(shí)踐

  1. 路由懶加載:使用 () => import('@/views/xxx.vue') 實(shí)現(xiàn)路由懶加載,減小首屏包體積。
  2. 動(dòng)態(tài)路由參數(shù):優(yōu)先使用動(dòng)態(tài)路由參數(shù)(如 /detail/:id)傳遞關(guān)鍵數(shù)據(jù),刷新頁面不丟失。
  3. 路由守衛(wèi):可添加全局前置守衛(wèi) router.beforeEach 實(shí)現(xiàn)登錄攔截(如未登錄跳轉(zhuǎn)到登錄頁)。

3.2 Pinia 使用最佳實(shí)踐

  1. 模塊化 Store:按功能劃分 Store(如 user.jscart.js),避免單個(gè) Store 過大。
  2. 組合式 API 寫法:使用 defineStore 的函數(shù)式寫法(而非對象式),更符合 Vue 3 的設(shè)計(jì)理念。
  3. 持久化插件:合理使用 pinia-plugin-persistedstate,只持久化必要的 state(如 Token、用戶信息),避免存儲(chǔ)敏感數(shù)據(jù)。

以上就是Vue3項(xiàng)目中多頁面路由配置與Pinia狀態(tài)管理的完全指南的詳細(xì)內(nèi)容,更多關(guān)于Vue3多頁面路由配置與Pinia狀態(tài)管理的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • 詳解如何用模塊化的方式寫vuejs

    詳解如何用模塊化的方式寫vuejs

    這篇文章主要介紹了詳解如何用模塊化的方式寫vuejs,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-12-12
  • Vue3中ref數(shù)組的監(jiān)聽實(shí)現(xiàn)方式

    Vue3中ref數(shù)組的監(jiān)聽實(shí)現(xiàn)方式

    Vue3中監(jiān)聽ref定義的數(shù)組,需根據(jù)監(jiān)聽需求選擇合適的監(jiān)聽方法,對于空數(shù)組,推薦使用深度監(jiān)聽來捕捉數(shù)組內(nèi)部變化,同時(shí),確保修改數(shù)組的方式是響應(yīng)式的,以保證監(jiān)聽器能正常工作,根據(jù)具體需求,可以選擇直接深度監(jiān)聽、監(jiān)聽數(shù)組長度變化或提取屬性監(jiān)聽等方案
    2025-10-10
  • vue?element表格某一列內(nèi)容過多,超出省略號(hào)顯示的實(shí)現(xiàn)

    vue?element表格某一列內(nèi)容過多,超出省略號(hào)顯示的實(shí)現(xiàn)

    這篇文章主要介紹了vue?element表格某一列內(nèi)容過多,超出省略號(hào)顯示的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • vue 實(shí)現(xiàn)dot-dropdown的實(shí)例代碼

    vue 實(shí)現(xiàn)dot-dropdown的實(shí)例代碼

    這篇文章主要介紹了vue實(shí)現(xiàn)dot-dropdown的相關(guān)操作,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2025-06-06
  • Vue中請求本地JSON文件并返回?cái)?shù)據(jù)的方法實(shí)例

    Vue中請求本地JSON文件并返回?cái)?shù)據(jù)的方法實(shí)例

    在前端開發(fā)過程當(dāng)中,當(dāng)后臺(tái)服務(wù)器開發(fā)數(shù)據(jù)還沒完善,沒法與咱們交接時(shí),咱們習(xí)慣在本地寫上一個(gè)json文件做模擬數(shù)據(jù)測試代碼效果是否有問題,下面這篇文章主要給大家介紹了關(guān)于Vue中請求本地JSON文件并返回?cái)?shù)據(jù)的相關(guān)資料,需要的朋友可以參考下
    2022-08-08
  • Vue3中事件總線mitt的使用方式

    Vue3中事件總線mitt的使用方式

    mitt又稱事務(wù)總線,是第三方插件,這篇文章主要為大家詳細(xì)介紹了Vue3中事件總線mitt的使用方式,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2025-03-03
  • vue實(shí)現(xiàn)web前端登錄頁數(shù)字驗(yàn)證碼

    vue實(shí)現(xiàn)web前端登錄頁數(shù)字驗(yàn)證碼

    這篇文章主要為大家詳細(xì)介紹了vue實(shí)現(xiàn)web前端登錄頁數(shù)字驗(yàn)證碼,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-06-06
  • Vue生命周期示例詳解

    Vue生命周期示例詳解

    這篇文章主要為大家詳細(xì)介紹了Vue生命周期的示例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-04-04
  • vue一直自動(dòng)換行的問題及解決

    vue一直自動(dòng)換行的問題及解決

    這篇文章主要介紹了vue一直自動(dòng)換行的問題及解決方案,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-03-03
  • Vue-cli配置打包文件本地使用的教程圖解

    Vue-cli配置打包文件本地使用的教程圖解

    這篇文章主要介紹了Vue-cli配置打包文件本地使用的教程圖解,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2018-08-08

最新評論

黄骅市| 英德市| 丹凤县| 大新县| 班玛县| 扎囊县| 礼泉县| 尤溪县| 来宾市| 岚皋县| 永安市| 视频| 淮南市| 赣榆县| 漯河市| 嘉定区| 巨野县| 永清县| 佛坪县| 右玉县| 石阡县| 敦煌市| 尼木县| 元氏县| 仲巴县| 沿河| 邵阳县| 三亚市| 远安县| 成都市| 海林市| 秀山| 肇庆市| 兴城市| 浠水县| 拜城县| 通化县| 泰安市| 黔江区| 专栏| 海伦市|