1.编程式的路由
编程式的导航 除了使用 创建 a 标签来定义导航链接 我们还可以用js的方法跳转页面
所谓的编程式路由,就是通过代码来实现路由。
和前面的router-link进行对比。router-link是通过点击来进行跳转的。而编程式路由,就没有router-link,而是通过代码直接跳转。
1.UI组件的跳转方式
<table cellspacing="0" cellpadding="0" border="1">
<tr>
<th>电影名字</th>
<th>上映时间</th>
<th>电影时长</th>
<th>电影海报</th>
</tr>
<tr v-for="item in movieList" :key="item.mId">
<td>{{item.title}}</td>
<td>{{item.year}}</td>
<td>{{item.longtime}}</td>
<!-- ui的方式通过path跳转 -->
<!-- ui的方式通过path跳转 -->
<!-- <td>
<router-link :to="{path:'/detail',query:{id:item.mId}}">
<img :src="item.small" width="100" height="110">
</router-link>
</td> -->
<!-- ui的方式通过name跳转 -->
<td>
<router-link :to="{name:'movieDetail',query:{id:item.mId}}">
<img :src="item.small" width="100" height="110">
</router-link>
</td>
</tr>
</table>
2.路由代码跳转
<template>
<div>
<h3>电影列表页</h3>
<table cellspacing="0" cellpadding="0" border="1">
<tr>
<th>电影名字</th>
<th>上映时间</th>
<th>电影时长</th>
<th>电影海报</th>
</tr>
<tr v-for="item in movieList" :key="item.mId">
<td>{{item.title}}</td>
<td>{{item.year}}</td>
<td>{{item.longtime}}</td>
<td @click="toDetail(item)">
<img :src="item.small" width="100" height="110">
</td>
</tr>
</table>
</div>
</template>
<script setup>
import axios from "axios"
import { onMounted,reactive,ref} from "vue";
//引入跳转路由
import {useRouter} from "vue-router"
var movieList=ref([])
onMounted(()=>{
axios.get("http://bufantec.com/api/douban/movie/in_theaters")
.then(res=>{
console.log(res);
const {data}=res.data;
movieList.value=data.list;
})
})
//跳转到详情页
const router=useRouter();
const toDetail=(item)=>{
//路由跳转和传递参数
//1.path 和query组合
// router.push({path:'/detail',query:{id:item.mId}})
//2.path 和params组合 不能一起使用
//router.push({path:'/detail',params:{id:item.mId}})
//3.name和query组合
//router.push({name:'movieDetail',query:{id:item.mId}})
//4.name和params 组合
router.push({name:'movieDetail',params:{id:item.mId}})
}
</script>
<style lang="scss">
table{
width: 500px;
margin: 0 auto;
td{
text-align: center;
}
}
</style>
3.useRoute()和 useRouter()的区别
这两个方法类似于$route 和 $router的区别。
useRoute():
route是一个跳转的路由对象,每一个路由都会有一个route对象,是一个局部的对象,可以获取对应的name,path,params,query等:
matched:
数组,包含当前匹配的路径中所包含的所有片段所对应的配置参数对象
name:
当前路径的名字,如果没有使用具名路径,则名字为空。
params:
对象,包含路由中的动态片段和全匹配片段的键值对
path:
字符串,等于当前路由对象的路径,会被解析为绝对路径,如 “/home/news”
query:
对象,包含路由中查询参数的键值对。例如,对于 /home/news/detail/01?favorite=yes ,会得到$route.query.favorite == ‘yes’
redirectedFrom
useRouter():
router是VueRouter的一个对象,通过Vue.use(VueRouter)和VueRouter构造函数得到一个router的实例对象,这个对象中是一个全局的对象,他包含了所有的路由包含了许多关键的对象和属性。
举例:history对象
$router.push({path:‘home’});本质是向history栈中添加一个路由,在我们看来是 切换路由,但本质是在添加一个history记录
方法:$router.replace({path:‘home’})
;//替换路由,没有历史记录