在页面开发中,我们经常需要实现点击跳转页面,并传递相应的参数过去在另一个页面展示出来。废话不说,直接上代码。
路由发出页面
<template>
<div id="home">
<header>头部</header>
<carousel class="index-carousel" :autoplay="true" :minSwipeDistance="40" :scrollPerPage="true" :speed="500" :perPage="1" :paginationPadding="10" :paginationSize="10" :loop="true">
<slide class="good" v-for="(good,index) in goods" :key="index">
<div v-for="(item,index) in good.list" v-if="index<=7" @click="setParams(item)">
{{item.name}}
</div>
</slide>
</carousel>
</div>
</template>
<script>
import {Carousel, Slide} from 'vue-carousel'
export default {
data(){
return {
goods:[
{list:[
{
name:'商品一',
path:'/Selist'
},
{
name:'商品二',
path:'/Selist'
},
{
name:'商品三',
path:'/Selist'
},
{
name:'商品四',
path:'/Selist'
},
{
name:'商品五',
path:'/Selist'
},
{
name:'商品六',
path:'/Selist'
},
{
name:'商品七',
path:'/Selist'
},
{
name:'商品八',
path:'/Selist'
}
]},
{list:[
{
name:'商品八',
path:'/Selist'
},
{
name:'商品七',
path:'/Selist'
},
{
name:'商品六',
path:'/Selist'
},
{
name:'商品五',
path:'/Selist'
},
{
name:'商品四',
path:'/Selist'
},
{
name:'商品三',
path:'/Selist'
},
{
name:'商品二',
path:'/Selist'
},
{
name:'商品一',
path:'/Selist'
}
]}
]
}
},
components:{
Carousel,
Slide
},
methods:{
setParams(i){//点击跳转函数
this.$router.push({
path:i.path,//跳转路由
query:{//参数对象
name:i.name
}
});
}
}
}
</script>
<style lang="scss" scoped>
.index-carousel{
margin-top:2em;
}
.good{
width:100%;
div{ width:25%;
height:5em;
line-height:5em;
float:left;
}
}
</style>
路由接收页面
<template>
<div>
<header>{{msg}}</header>
</div>
</template>
<script>
export default{
data(){
return {
msg:''
}
},
methods:{
getParams(){//接收函数
console.log(this.$router)
this.msg = this.$router.history.current.query.name;
}
},
created() {//在模板编译进路由前调用created方法,触发接收函数
var self = this;
self.getParams();
}
}
</script>
<style>
</style>
这里,我们可以看一下拿到的路由形式,以便我们获取传过来的参数(console.log(this.$router))。
由上图可以看到,我们传过来的值在current下的query中,直接获取就好。
注意
params和query都可以用于存放参数,但是有几点不同:
1、关于带参数的路由总结如下:
无论是直接路由“path" 还是命名路由“name”,带查询参数query,地址栏会变成“/url?查询参数名=查询参数值“;
直接路由“path" 带路由参数params params 不生效;
命名路由“name" 带路由参数params 地址栏保持是“/url/路由参数值”;
2、设置路由map里的path值:
带路由参数params时,路由map里的path应该写成: path:'/Selist/:name' ;
带查询参数query时,路由map里的path应该写成: path:'/Selist' ;
3、获取参数方法:
在组件中: {{$route.params.name}}
在js里: this.$route.params.name