vue-router路由跳转&路由传参
对于大多数单页面应用,都推荐使用官方支持的 vue-router 库。更多细节可以移步 vue-router文档 。
跳转方式一:声明式导航router-link
<router-link :to="需要跳转到的页面的路径">
<router-link :to="home">//路由链接
<!--或<router-link :to="{name:'home'}">-->
<!--或<router-link :to="{path:'/home'}"> -->//name,path都行, 建议用name
<router-view></router-view>//用于渲染当前路由组件
使用replace不会有浏览历史,所以不能点击返回上一个页面
<router-link to="/shop/goods" replace>点餐</router-link>
跳转方式二:编程式导航
$route:表示当前页面
this.$router.push(path) //: 相当于点击路由链接(可以返回到当前路由界面)
this.$router.push(‘/home’)
this.$router.push({name:’home’})
this.$router.push({path:’/home’})this.$router.replace(path) //: 用新路由替换当前路由(不可以返回到当前路由界面)
- this.$router.back() //: 请求(返回)上一个记录路由
- this.$router.go(-1) //:请求(返回)上一个记录路由
this.$router.go(1) //: 请求下一个记录路由
路由传参
声明式导航router-link路由传参
方式 1: 路由路径携带参数(param/query)
1) 配置路由
children: [
{
path: 'mdetail/:id', component: MessageDetail
}
]
2) 路由路径
<router-link :to="'/home/message/mdetail/'+m.id">{
{m.title}}</router-link>
3) 路由组件中读取请求参数
this.$route.params.id
方式 2: 属性携带数据
<router-view :msg="msg"></router-view>
<template>
<div>
<h2>About</h2>
<p>{
{msg}}</p>
<input type="text">
</div>
</template>
<script>
export default {
props: {
msg: String
}
}
</script>
变成式路由导航传参
使用query传参
1.路由配置:
name: 'home',
path: '/home'
2.跳转:
this.$router.push(
{
name:'home',
query: {id:'1'}
}
)
或
this.$router.push(
{
path:'/home',
query: {id:'1'}}
)
3.获取参数
html取参: $route.query.id
script取参: this.$route.query.id
使用params传参
1.路由配置:
name: 'home',
path: '/home/:id'(或者path: '/home:id')
2.跳转:
this.$router.push(
{
name:'home',
params: {id:'1'}
}
)
注意:
// 只能用 name匹配路由不能用path
// params传参数(类似post) 路由配置 path: "/home/:id" 或者 path: "/home:id"否则刷新参数消失
3.获取参数
html取参:$route.params.id
script取参:this.$route.params.id
直接通过path传参
1.路由配置:
name: 'home',
path: '/home/:id'
2.跳转:
this.$router.push({path:'/home/123'})
或者:
this.$router.push('/home/123')
3.获取参数:
this.$route.params.id
params和query的区别
query类似 get,跳转之后页面 url后面会拼接参数,类似?id=1。
非重要性的可以这样传,密码之类还是用params,刷新页面id还在。
params类似 post,跳转之后页面 url后面不会拼接参数。
完整例子
在putId.vue文件中
<template>
<li @click="change">编程式路由传参</li>
</template>
<script>
export default {
data () {
return {
id:2, //需要传递的参数
}
},
methods:{
change(){
this.$router.push({
//核心语句
path:'/getId', //跳转的路径
query:{
//路由传参时push和query搭配使用 ,作用时传递参数
id:this.id ,
}
})
}
}
}
</script>
在getId.vue文件中
<template>
<div>
{
{id}}
</div>
</template>
<script>
export default{
data(){
return{
id:'',
}
},
created(){
this.id = this.$route.query.id,
console.log(this.id)
}
}
</script>
this.$router.replace{path:‘/’ }类似
还没有评论,来说两句吧...