Skip to content
索引

vue-router

下载最新版

@next表示下载最新版

sh
npm i vue-router@next -s
npm i vue-router@next -s

src 下新建 router 文件夹,新建 index.ts

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

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'home',
    component: () => import('../views/Home.vue')
  }
]
const router = createRouter({
  history: createWebHistory(),
  routes
})

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

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'home',
    component: () => import('../views/Home.vue')
  }
]
const router = createRouter({
  history: createWebHistory(),
  routes
})

export default router

main.ts 中加入

ts
import router from './router'
...
const app = createApp(App)
app.use(router).mount("#app")
import router from './router'
...
const app = createApp(App)
app.use(router).mount("#app")

App.vue使用router-view标签即可渲染home页面

传参

  • $router 是路由操作对象,只写对象

  • $route 路由信息对象,只读对象

  • name 可以使用 query 和 params 传参

  • path 不能使用 params 传参,只能使用 query 传参

  • query 相当于 get 请求,页面跳转的时候,可以在地址栏看到请求参数,刷新后依旧存在

  • params 相当于 post 请求,参数不会再地址栏中显示,刷新后不复存在

js
this.$router.push({ path: 'world', query: { id: 'id' } })
this.$router.push({ name: 'world', params: { id: 'id' } })
this.$router.push({ path: 'world', query: { id: 'id' } })
this.$router.push({ name: 'world', params: { id: 'id' } })

接收

js
this.$route.query
this.$route.params
this.$route.query
this.$route.params

路由占位符

声明接收 params 参数,如果不传递 params 或传递 params 为空,都会直接报错,Uncaught Error: Missing required param "code"

js
 {
    path: "/:code",
    name: "home",
    component: () => import(/* webpackChunkName: "about" */ "../views/Home.vue")
  }
 {
    path: "/:code",
    name: "home",
    component: () => import(/* webpackChunkName: "about" */ "../views/Home.vue")
  }
js
router.push({ name: 'home', query: { k: 1 } })
// Uncaught Error: Missing required param "code"
router.push({ name: 'home', params: { code: '' }, query: { k: 2 } })
// Uncaught Error: Missing required param "code"
router.push({ name: 'home', query: { k: 1 } })
// Uncaught Error: Missing required param "code"
router.push({ name: 'home', params: { code: '' }, query: { k: 2 } })
// Uncaught Error: Missing required param "code"

如果希望 params 参数是可选传递,可传可不传,在占位符后面加个?号即可

js
 {
    path: "/:code?",
    name: "home",
    component: () => import(/* webpackChunkName: "about" */ "../views/Home.vue")
  }
 {
    path: "/:code?",
    name: "home",
    component: () => import(/* webpackChunkName: "about" */ "../views/Home.vue")
  }

路由传递 props 的三种写法

路由跳转

ts
<script lang="ts" setup>
  import {useRouter} from "vue-router" const router = useRouter() function
  goSearch(){' '}
  {router.push({ name: 'home', params: { code: '111' }, query: { key: 222 } })}
</script>
<script lang="ts" setup>
  import {useRouter} from "vue-router" const router = useRouter() function
  goSearch(){' '}
  {router.push({ name: 'home', params: { code: '111' }, query: { key: 222 } })}
</script>

布尔值

ts
{
    path: "/:code",
    name: "home",
    component: () => import("../views/Home.vue"),
    props:true // 会将params传递至该组件中
}
{
    path: "/:code",
    name: "home",
    component: () => import("../views/Home.vue"),
    props:true // 会将params传递至该组件中
}

组件中正常使用 props 接收即可

ts
<script lang="ts" setup>
import { defineProps } from "vue"
const props = defineProps<{
  code: string
}>()
</script>
<script lang="ts" setup>
import { defineProps } from "vue"
const props = defineProps<{
  code: string
}>()
</script>

对象

ts
{
    path: "/:code",
    name: "home",
    component: () => import("../views/Home.vue"),
    props: { a: 1, b: 2 }
}
{
    path: "/:code",
    name: "home",
    component: () => import("../views/Home.vue"),
    props: { a: 1, b: 2 }
}
ts
<script lang="ts" setup>
import { defineProps } from "vue"
const props = defineProps<{
  a: number
  b: number
}>()
</script>
<script lang="ts" setup>
import { defineProps } from "vue"
const props = defineProps<{
  a: number
  b: number
}>()
</script>

函数

ts
{
    path: "/:code",
    name: "home",
    component: () => import("../views/Home.vue"),
    props: $router => {
      return { a: $router.params.code, b: $router.query.key }
    }
}
{
    path: "/:code",
    name: "home",
    component: () => import("../views/Home.vue"),
    props: $router => {
      return { a: $router.params.code, b: $router.query.key }
    }
}
ts
<script lang="ts" setup>
import { defineProps } from "vue"
const props = defineProps<{
  a: string
  b: number
}>()
</script>
<script lang="ts" setup>
import { defineProps } from "vue"
const props = defineProps<{
  a: string
  b: number
}>()
</script>

router-view

router-view 是路由的占位标签,会根据当前路径将该位置替换为该路径相匹配的 vue 组件

父组件中使用 router-view,会根据子组件的路由自动匹配显示相应内容

router-view 父子组件通信

父组件

父组件传递给子组件一个方法 getTitle

js
<router-view :hdId="hdidArr" @getTitle="showtitle" />
<router-view :hdId="hdidArr" @getTitle="showtitle" />

子组件

子组件通过 getTitle 这个方法传值

js
this.$emit('getTitle', this.$route.query.tit)
this.$emit('getTitle', this.$route.query.tit)

e 即是子组件传过来的值

父组件通过传递给子组件方法 getTitle 绑定的方法 showtitle 进行接收

js
 showtitle (e) {
            this.$message.success(e)
        }
 showtitle (e) {
            this.$message.success(e)
        }

element-plus 中 el-menu 内置 vue-route,设置 router 属性为 true 后,el-menu-item 中可以使用 index 属性进行路径跳转,使用 route 属性进行路径传参

vue
<el-menu-item
  v-for="item in items"
  :key="item.id"
  :index="item.url"
  :route="{ path: item.url, query: { name: item.id } }"
>
</el-menu-item>
<el-menu-item
  v-for="item in items"
  :key="item.id"
  :index="item.url"
  :route="{ path: item.url, query: { name: item.id } }"
>
</el-menu-item>

旧版本解决报错

js
const originalPush = VueRouter.prototype.push

VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
const originalPush = VueRouter.prototype.push

VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

子路由path

不带 / (推荐)

子路由 path 路径前不写 / ,会自动拼接上父路由的 path 路径

$router.push方法书写跳转地址时,需要与父级路由地址一同书写

浏览器地址栏显示: http:xxxx/父路由路径/子路由路径

js
$router.push('/父路由路径/子路由路径')
$router.push('/父路由路径/子路由路径')

带 /

子路由 path 路径前不写 / ,则不会自动拼接上父路由的 path 路径

浏览器地址栏显示: http:xxxx/子路由路径

js
$router.push('/user')
$router.push('/user')

Released under the MIT License.