命名路由的作用:简化路由跳转,无需使用path硬编码。除了router-link外其实我们也可以使用a标签和href属性来进行跳转。但如此做会造成页面刷新(闪了一下),所以我们还是建议使用router-link
router中的定义方式如下:
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
const routes: Array<RouteRecordRaw> = [
{
path: '/',
// 命名路由写法
name: 'Login',
component: () => import('../components/login.vue'),
},
{
// 非命名路由写法
path: '/reg',
component: () => import('../components/reg.vue'),
},
]
const router = createRouter({
history: createWebHashHistory(),
routes,
})
export default router
在App.vue中使用
<template>
<h1>小满最骚</h1>
// 注意:若要使用命名路由跳转方式则to中的内容必须是一个对象(即必须借助v-bind进行绑定)
<router-link :to="{ name: 'Login' }">点击此处跳转至Login</router-link>
<br>
<router-link to="/reg">点击此处跳转至Reg</router-link>
<router-view></router-view>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
</script>
<style scoped></style>
编程式导航:无需router-link标签即可实现跳转、传参等操作,通过在脚本中使用useRouter并调用API实现
字符串模式:
<template>
<h1>小满最骚</h1>
<button @click="toPage('/')">Login</button>
<br />
<button @click="toPage('/reg')">Reg</button>
<router-view></router-view>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const toPage = (url: string) => {
router.push(url)
}
</script>
<style scoped></style>
无需多余的操作,直接push到url对应的地址,但要注意url必须是path
对象模式
<template>
<h1>小满最骚</h1>
<button @click="toPage('/')">Login</button>
<br />
<button @click="toPage('/reg')">Reg</button>
<router-view></router-view>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const toPage = (url: string) => {
router.push({
path: url,
})
}
</script>
<style scoped></style>
将router.push()的内容由字符串改为配置对象,path对应的url即为要跳转到的url
命名式
<template>
<h1>小满最骚</h1>
<button @click="toPage('Login')">Login</button>
<br />
<button @click="toPage('Reg')">Reg</button>
<router-view></router-view>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const toPage = (name: string) => {
router.push({
name,
})
}
</script>
<style scoped></style>
在router.push配置对象中把path改为name,需要在index.ts里指定路由的名字
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
const routes: Array<RouteRecordRaw> = [
{
path: '/',
// 命名路由
name: 'Login',
component: () => import('../components/login.vue'),
},
{
path: '/reg',
name: 'Reg',
component: () => import('../components/reg.vue'),
},
]
const router = createRouter({
history: createWebHashHistory(),
routes,
})
export default router