vue的三种传参方式

传参:

  1. 页面式(html)标签路由跳转传参 ----- router-link(其实就是a标签)

  2. js编程式路由跳转 ----- this.$router.push() // params query

  3. 路由组件传参 ----- 在路由配置中用分号拼接参数

获取参数:

  1. this.$router.params ----- 搭配路由的name属性,参数作为路由的一部分,不会在url显示

  2. this.$router.query ----- 使用path来匹配路由,可以在url看到?后面的就是传递的参数

一、router-link

<router-link :to="{path:'/news/detail',query:{id:1}}">详情</router-link>

使用path + 路径,query + 参数。则用this.$route.query.id取值。

<router-link :to="{name:'newsDetail',params:{id:1}}">详情</router-link>

使用name +路由名称,params + 参数。则用this.$route.params.id取值。

二、this.$router.push() ----- key,value键值对的形式

  1. query 显示在url
// 传参
sendData(){
    this.$router.push({ 
        path: './describe', 
        query: { 
            id:id,
            title:title
        }
    })  
}
// 接收参数
this.$route.query.id
this.$route.query.title
  1. params 不会显示在url
// 传参
sendData(){
    this.$router.push({ 
        name: './describe', 
        params: { 
            id:id,
            title:title
        }
    })  
}
// 接收参数
this.$route.params.id
this.$route.params.title

三、路由组件传参

路由部分:

let routes = [
{
    path: '/news',
    name: 'news',
    props: true,
    meta: {},
    component: () => import('@/page/news.vue')
},{
    path: '/newsDetail/:id',
    name: 'newsDetail',
    props: true,
    meta: {},
    component: () => import('@/page/newsDetail.vue')
}  
]

path后面跟占位符,props设置为波尔类型,true。跳转页面时使用this.$router.push传参。

下面是取值的方式

export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: '123
    }
  },
  props:['id'],
  mounted(){
    console.log(this.$route.params.id, this.id)
  }
}

取值时,方法1:可以直接使用this.$route.params.id取值。

方法2:也可以先放到props中,就可以直接用this.id拿到了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值