vue-router传递参数分为两大类
- 编程式的导航 router.push
- 声明式的导航
编程式的导航 router.push
编程式导航传递参数有两种类型:字符串、对象。
字符串
字符串的方式是直接将路由地址以字符串的方式来跳转,这种方式很简单但是不能传递参数:
this.$router.push("home");
对象
想要传递参数主要就是以对象的方式来写,分为两种方式:命名路由、查询参数,下面分别说明两种方式的用法和注意事项。
命名路由
命名路由的前提就是在注册路由的地方需要给路由命名如:
命名路由传递参数需要使用params来传递,这里一定要注意使用params不是query。目标 页面接收传递参数时使用params
特别注意:命名路由这种方式传递的参数,如果在目标页面刷新是会出错的
使用方法如下:
this.$router.push({ name: 'news', params: { userId: 123 }})
代码如下:
<template> <div class="hello"> <h1>{{ msg }}</h1> <button @click="routerTo">click here to news page</button> </div> </template> <script> export default { name: 'HelloWorld', data () { return { msg: 'Welcome to Your Vue.js App' } }, methods:{ routerTo(){ this.$router.push({ name: 'news', params: { userId: 123 }}); } } } </script> <style> </style>
接受传递的参数:
<template> <div> this is the news page.the transform param is {{this.$route.params.userId}} </div> </template> <script> </script>