demo\src\router\index.js
import { createRouter, createWebHashHistory, createWebHistory } from "vue-router"
const routes = [
{
path: "/",
//alias:"/home", //定义别名 http://localhost:5173/home
alias:["/home","/index"], // http://localhost:5173/home http://localhost:5173/index
// component: () => import("../views/index.vue")
component: () => import("@/views/index.vue")
},
{
path: "/content", // 使用查询字符串传递参数 http://localhost:5173/content?id=100&title=邓瑞编程
component: () => import("@/views/content.vue")
},
{
path: "/user/:id/name/:name", // 使用路径传递参数 http://localhost:5173/user/007/name/邓瑞
component: () => import("@/views/user.vue")
},
{
//可选参数 name? 表示该参数不是必需的
path: "/userHistory/:id/name/:name?", // http://localhost:5173/userHistory/007/name
name: "history", // 定义路由名称
component: () => import("@/views/user.vue")
},
]
const router = createRouter({
// 使用url的#符号之后的部分模拟url路径的变化,因为不会触发页面刷新,所以不需要服务端支持
// history: createWebHashHistory(),
history: createWebHistory(),
routes
})
export default router
demo\src\views\index.vue
<script setup>
import { useRouter } from 'vue-router';
const router = useRouter()
let userId = 100
let userName = "邓瑞"
const goTo = ()=> {
//router.push("/user/007/name/邓瑞")
//router.push({ path: '/content', query: { id: 200, title: '邓瑞' } })
router.push({ name: 'history', params: { id: '300', name: '邓瑞编程' }})
}
</script>
<template>
首页 - dengruicode.com <hr>
<router-link to="/content?id=100&title=邓瑞编程">查询字符串传参</router-link> <br>
<router-link to="/user/007/name/邓瑞">路径传参</router-link> <br>
<!-- 动态属性绑定 -->
<router-link :to="{ path: '/content', query: { id: 200, title: '邓瑞' } }">查询字符串传参 - 动态属性绑定</router-link> <br>
<router-link :to="{ path: `/user/${userId}/name/${userName}` }">路径传参 - 动态属性绑定</router-link> <br>
<!-- 定义路由名称 -->
<router-link :to="{ name: 'history', params: { id: '300', name: '邓瑞编程' }}">路径传参 - 定义路由名称</router-link> <br>
<!-- 编程式导航 -->
<button @click="goTo()">编程式导航</button>
</template>
<style scoped>
</style>
4.router-link、定义别名、定义路由名称、编程式导航
-- 未经授权禁止转载 --