创建路由器
router/index.ts
// 创建一个路由器,并暴露出去
// 引入路由器
import { createRouter,createWebHistory } from "vue-router";
// 引入组件
import Home from "../pages/Home.vue";
import News from "../pages/News.vue";
import About from "../pages/About.vue";
import Detail from "../pages/Detail.vue";
// 创建路由器
const router = createRouter({
history:createWebHistory(), // 路由器工作模式
routes:[//路由匹配规则(路径对组件)
{
name:'zhuye',
path:'/home',
component:Home
},
{
path:'/news',
component:News,
// 嵌套路由
children:[{
name:'xiang',
path:"detail",
component:Detail
}]
},
{
path:'/about',
component:About
},
]
})
export default router
主页App.vue引入路由器
<!-- html -->
<template>
<div class="app">
<!-- 标题 -->
<Header/>
<!-- 导航区 -->
<div class="navigate">
<RouterLink :to="{name:'zhuye'}" active-class="active">首页</RouterLink>
<RouterLink :to="{path:'/news'}" active-class="active">新闻</RouterLink>
<RouterLink :to="{path:'/about'}" active-class="active">关于</RouterLink>
</div>
<!-- 展示区 -->
<div class="main-content">
<RouterView></RouterView>
</div>
</div>
</template>
<script lang="ts" name="APP" setup>
import { RouterView,RouterLink } from 'vue-router';
import Header from './components/Header.vue';
</script>
新闻页News.vue(给路由指向页query传值)
<template>
<div class="news">
<!-- 导航区 -->
<ul>
<li v-for="item in newList" :key="item.id">
<!-- query 传值 -->
<!-- <RouterLink :to="`/news/detail?id=${item.id}&title=${item.title}&content=${item.content}`">{{ item.title }}</RouterLink> -->
<RouterLink
:to="{
name:'xiang',
// path:'/news/detail',
query:{
id:item.id,
title:item.title,
content:item.content
}
}">
{{ item.title }}
</RouterLink>
<!-- params 传值 -->
<!-- <RouterLink :to="{path:'/news/detail'}">{{ item.title }}</RouterLink> -->
</li>
</ul>
<!-- 展示区 -->
<div class="news-content">
<RouterView></RouterView>
</div>
</div>
</template>
<script setup lang="ts" name="News">
import { reactive } from 'vue';
let newList = reactive([
{
id:'news01',title:'好消息!好消息!',content:'快要发钱了'
},
{
id:'news02',title:'如何一夜暴富',content:'跟我学IT'
},
{
id:'news03',title:'震惊!万万没想到',content:'明天周一'
},
{
id:'news04',title:'震惊!干了188天',content:'青海持续干旱,188天不下雨了'
},
])
</script>
新闻详情页Detail.vue(接收query传值)
<template>
<ul class="news-list">
<li>编号:{{ query.id }}</li>
<li>标题:{{ query.title }}</li>
<li>内容:{{ query.content }}</li>
</ul>
</template>
<script lang="ts" setup name="Detail">
import { useRoute } from 'vue-router';
import { toRefs } from 'vue';
// 使用路由hooks
let route = useRoute()
// 响应式对象解构赋值,需要使用toRefs,否则变成了普通对象
let {query} = toRefs(route)
console.log(route.query)
</script>