VueRouter4 路由代碼解析

一、路由初始化

1.1. Vue2和Vue3路由創(chuàng)建比對

image.png

1.2. Vue3路由解析

image.png

1.3. 基礎(chǔ)代碼解析

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

// createRouter 創(chuàng)建路由實例,===> new VueRouter()
// 1. history模式: createWebHistory()   http://xxx/user
// 2. hash模式: createWebHashHistory()  http://xxx/#/user

// vite 的配置 import.meta.env.BASE_URL 是路由的基準地址,就是 vite.config.js 中的 base 配置項
// https://vitejs.dev/guide/build.html#public-base-path

// 如果將來你部署的域名路徑是:http://xxx/my-path/user
// vite.config.ts  添加配置  base: my-path,路由這就會加上 my-path 前綴了

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: []
})

export default router

import.meta.env.BASE_URL的值就是vite.config.js中的base配置項(默認 /

vite.config.js

export default defineConfig({
  plugins: [
    vue(),
  ],
  base: '/', //import.meta.env.BASE_URL的值就是base配置項目
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  }
})

1.4. 路由的使用

<script setup>
// 這樣不行,this沒有
// const goList = () => {
//     this.$router.push('/lish')
// }

import { useRouter, useRoute } from 'vue-router'
// 在vue3 compositionAPI中
// 1. 獲取路由對象 router useRouter
//    const router = userRouter()
// 2. 獲取路由參數(shù) route useRoute()
//    const route = useRooute()
const router = useRouter()
const goList = () => {
  router.push('/list')
}
</script>

<template>
  <div>
    appVue
    <button @click="$router.push('/home')">to Index</button>
    <button @click="goList">to listPage</button>
  </div>
</template>

<style scoped></style>

二、總結(jié)

image.png

vite環(huán)境變量地址:https://cn.vitejs.dev/guide/env-and-mode.html

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容