Vue Router 是 Vue.js 官方的路由管理器。它和 Vue.js 的核心深度集成,让构建单页面应用变得易如反掌。包含的功能有:
- 嵌套的路由/视图表
- 模块化的、基于组件的路由配置
- 路由参数、查询、通配符
- 基于 Vue.js 过渡系统的视图过渡效果
- 细粒度的导航控制
- 带有自动激活的 CSS class 的链接
- HTML5 历史模式或 hash 模式,在 IE9 中自动降级
- 自定义的滚动条行为
vue-router传参两种方式:params和query
params、query是什么?
params:/router1/:id ,/router1/123,/router1/789 ,这里的id叫做params query:/router1?id=123 ,/router1?id=456 ,这里的id叫做query。
方法1:
query 方式传参和接收参数
传参:
this.$router.push({
path:'/openAccount',
query:{id:id}
});
接收参数:
this.$route.query.id
注意:传参是this.$router,接收参数是this.$route 两者区别:
$router为VueRouter实例,想要导航到不同URL,则使用$router.push方法
$route为当前router跳转对象,里面可以获取name、path、query、params等
方法2:
params方式传参和接收参数
传参:
this.$router.push({
name:'/openAccount',
params:{
id: id
}
})
接收参数: this.$route.params.id
注意:params传参,push里面只能是 name:'xxxx',不能是path:'/xxx',因为params只能用name来引入路由,如果这里写成了path,接收参数页面会是undefined!!!
二者还有点区别,可以理解为:query相当于get请求,页面跳转的时候,可以在地址栏看到请求参数,而params相当于post请求,参数不会再地址栏中显示
router.js
export default new Router({
routes: [
{
path: '/',
name: 'login',
component: Login
},
{
path: '/register',
name: 'register',
component: Register
}
})
组件(传参):
<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: 'register', params: { userId: 123 }});//params方式 这里的name值是在定义route.js时中的name
//this.$router.push({ path: '/register', query: { userId: 123 }}); //query方式
}
}
}
</script>
<style>
</style>
组件(接收参数)
<template>
<div>
{{this.$route.params.userId}}或者{{this.$route.params.userId}}
</div>
</template>
<script>
</script>
总结
以上所述是小编给大家介绍的vue-router传参的两种方式,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!