路由:
1.安装所需要的依赖
npm i vue-router
2.定义路由(包括嵌套路由)
import {createRouter,createWebHistory} from "vue-router"
import Home from "@/views/Home.vue"
import About from "@/views/About.vue"
import News from "@/views/News.vue"
const router=createRouter({
history:createWebHistory(),
routes:[
{
path: '/',
redirect: '/home', // 重定向到 home 路由
},
{
name:'zhuye',
path:'/home',
component:Home
},
{
name:'xinwen',
path:'/news',
component:News,
children:[
{
name:'xiang',
path:'detail',
component:Detail
}
]
},
{
name:'guanyu',
path:'/about',
component:About
}
]
})
export default router
3.注册路由:
import { createApp } from 'vue'
import App from './App.vue'
import router from "@/router/index"
const app = createApp(App)
app.use(router)
app.mount('#app')
4.使用路由:(路由的query传参)
<template>
<div>
这个是一个导航的try
<RouterLink :to="{
path:'/news',
query:{
a:1,
b:2
}
}">到新闻页去</RouterLink>
</div>
<br>
<div>
<RouterView></RouterView>
</div>
</template>
<script setup lang="ts">
import { RouterLink,RouterView } from 'vue-router';
</script>
<style scoped>
</style>
新闻组件
<template>
<div>这是新闻界面,获得的参数是:{{ a }},{{ b }}</div>
</template>
<script setup lang="ts">
import {useRoute} from "vue-router"
const route=useRoute()
const {a,b}=route.query
console.log(route.query)
</script>
<style scoped>
</style>
编程式路由导航(代替routerlink):
//三秒后跳转到指定路由(news组件)
import {onMounted} from 'vue'
import {useRouter} from 'vue-router'
const router = useRouter()
onMounted(()=>{
setTimeout(()=>{
router.push('/news')//push函数的写法和to写法一样,可以传递对象(也和to一样)
},3000)//push方法有历史记录
})
多个routerlink和routerview让其对应渲染:
<template>
<div>
<!-- 导航链接 -->
<RouterLink to="/home">Home</RouterLink>
<RouterLink to="/news">News</RouterLink>
<RouterLink to="/about">About</RouterLink>
<!-- 嵌套路由视图 -->
<div v-if="$route.path.startsWith('/news')">
<!-- 只有当路由是新闻相关时才显示新闻的视图 -->
<RouterView />
</div>
<div v-if="$route.path.startsWith('/about')">
<!-- 只有当路由是关于我们相关时才显示关于我们的视图 -->
<RouterView />
</div>
</div>
</template>
<script setup>
import { RouterLink, RouterView } from 'vue-router';
</script>