君陌离的博客

vuePress-theme-reco 君陌离    2018 - 2020
君陌离的博客 君陌离的博客

Choose mode

  • dark
  • auto
  • light
首页
我的作品
  • 项目橱窗
  • blog模板
分类
  • 数据库
  • CSS
  • 摘记
  • JS
  • Node
  • Vue
  • React
  • GIT
  • Promise
  • Liunx
  • Xshell
  • ajax
  • WINDOWS
  • Python
  • 随笔
  • 脚手架
  • node
  • 自动化
标签
笔记
时间线
About Me
  • 关于我
  • 赞赏
Contact
  • GitHub
  • QQ
author-avatar

君陌离

70

文章

90

标签

首页
我的作品
  • 项目橱窗
  • blog模板
分类
  • 数据库
  • CSS
  • 摘记
  • JS
  • Node
  • Vue
  • React
  • GIT
  • Promise
  • Liunx
  • Xshell
  • ajax
  • WINDOWS
  • Python
  • 随笔
  • 脚手架
  • node
  • 自动化
标签
笔记
时间线
About Me
  • 关于我
  • 赞赏
Contact
  • GitHub
  • QQ
  • HTML5

  • JS

  • 微信小程序

  • 数据库

  • React

  • Vue

    • Vue知识点
    • Vuex中的核心内容
    • Vue三种传参方式
    • Vue的钩子函数[路由导航守卫、keep-alive]
    • Vue自定义指令,插槽,监听
    • Vue生命周期
  • vuepress

Vue三种传参方式

vuePress-theme-reco 君陌离    2018 - 2020

Vue三种传参方式

君陌离 2020-08-07 14:44:26 VueVue传参

# 传参方式

    1. 页面式(html)标签路由跳转传参 ----- router-link(其实就是a标签)
    1. js编程式路由跳转 ----- this.$router.push() // params query
    1. 路由组件传参 ----- 在路由配置中用分号拼接参数

# 获取参数

    1. this.$router.params ----- 搭配路由的name属性,参数作为路由的一部分,不会在url显示
    1. this.$router.query ----- 使用path来匹配路由,可以在url看到?后面的就是传递的参数

# 一、router-link

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

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

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

使用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
        }
    })  
}
1
2
3
4
5
6
7
8
9
10
// 接收参数
this.$route.query.id
this.$route.query.title
1
2
3
    1. params 不会显示在url
// 传参
sendData(){
    this.$router.push({
        name: './describe',
        params: {
            id:id,
            title:title
        }
    })  
}
1
2
3
4
5
6
7
8
9
10
// 接收参数
this.$route.params.id
this.$route.params.title
1
2
3

# 三、路由组件传参

  • 路由部分:
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')
}  
]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

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
2
3
4
5
6
7
8
9
10
11
12

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

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

欢迎来到 您的站点名称($site.title)
看板娘