在 Vue Router 中,动态路由传值通常有两种方式:使用params和使用query。
使用params传值:
-
配置动态路由时,在路由路径中使用冒号
:来定义参数,例如:
const routes = [
// 动态路由路径参数以 : 开头
{ path: '/content/:aid', component: content },
];
-
传递参数时,可以直接在
<router-link>标签的to属性中拼接参数值,或者使用对象传参的方式。例如:- 直接传参(单参或多参):
<router-link to="/content/paramValue">或<router-link :to="'/content/' + key">(其中key是动态值) - 对象传参(单参或多参):
<router-link :to='{ name: "content", params: { aid: "paramValue" }}'></router-link>
- 直接传参(单参或多参):
-
在接收参数的组件中,可以通过
this.$route.params来获取动态路由传递的值。例如:this.$route.params.aid。
使用query传值:
-
配置路由与普通路由相同,无需特殊定义参数。
-
传值时,在
<router-link>标签的to属性中通过?后面拼接参数,或者使用对象传参的方式。例如:-
直接传参(单参或多参):
<router-link :to="/content?aid=paramValue"> -
对象传参(单参或多参):
- 使用路由名字:
<router-link :to='{ name: "content", query: { aid: "paramValue" }}'></router-link> - 使用路由路径:
<router-link :to='{ path: "/content", query: { aid: "paramValue" }}'></router-link>
- 使用路由名字:
-
-
在接收参数的组件中,通过
this.$route.query来获取参数值。例如:this.$route.query.aid。
另外,还可以使用编程式导航进行传值,例如通过this.$router.push()方法,并传入相应的路径和参数对象。
需注意,使用params传值时,刷新页面可能会导致参数丢失,因为params是通过路由的路径进行传递的;而query传值的参数会显示在 URL 中,刷新页面后参数仍然存在。同时,确保在组件的生命周期钩子(如created或mounted)中获取路由参数,以确保能够正确获取到传递的值。
以下是一个使用params传值的示例代码:
定义路由:
import Vue from 'vue';
import VueRouter from 'vue-router';
const routes = [
// 动态路由路径参数以 : 开头
{ path: '/news/:aid', component: NewsComponent },
];
const router = new VueRouter({
routes
});
export default router;
传递参数(在某个组件中):
<router-link :to="'/news/' + newsId"> 前往新闻详情页 </router-link>
接收参数(在 NewsComponent 组件中):
export default {
name: 'NewsComponent',
data() {
return {};
},
mounted() {
// 通过 this.$route.params 获取动态路由的参数
const aid = this.$route.params.aid;
console.log(aid);
}
}