vue-router参数传递

vue-router参数传递

通过 :to 和 query 进行参数传递

URL 是表示资源位置的字符串。

解析URL (维基百科) <scheme> 方案+<host> 主机+<port> 端口+<hostport> 主机及端口+<path> 路径+<query> 请求+<fragment> 片段+<host-specific> 主机待定

其中,query为请求

参考代码:

在入口vue文件App.vue中配置对应Profile文件

<!-- vue2 App.vue -->
<template>
  <!-- 注意:此处to加了:即v-bind:之后属性值才会是对象,否则就是普通的字符串 -->
  <router-link :to="{path:'/profile',query:{name:'zzwi',gender:'man'}}">Profile</router-link>
</template>
<!-- vue2 Profile.vue -->
<template>
  <div>
    <h2>我是Profile标题</h2>
    <p>我是Profile内容</p>
    <p>{{$route.query.name}}</p>
    <p>{{$route.query.gendle}}</p>
  </div>
</template>

运行效果

我是Profile标题

我是Profile内容

zzwi

man

通过 methods 和 query 进行参数传递

在入口vue文件App.vue中设置methods

// vue2
// App.vue
<template>
  <div>
    <button @click="profileClick">Profile</button>
  </div>
</template>

<script>
  export default {
    name: 'App',
    methods: {
      profileClick() {
        this.$router.push({
          path: '/profile',
          query: {
            name: 'zzwi',
            gendle: 'man'
          }
        })
      }
    }
}
</script>

通过 params 进行参数传递

通过配置路由格式

{
    // 配置动态路由
    path:'/user/:id'
}

在入口文件App.vue的路径传递方式:在path后面跟上对应的值

<template>
  <div>
    <router-link to="/user/123"></router-link>    
  </div>
</template>

之后便能生成路径:/user/123

this.$router.push() 和 params

在router文件夹的入口文件中配置路由

// vue2
// router/index.js
const routes = [
  {
    path: '/user'
    name: 'User',
    // 懒加载
    component: () => import("../views/User.vue")
  }
]

通过name获取页面,传递params

this.$router.push({name: 'User',params:{a:aaa,b:bbb,c:ccc}})

之后就可以在目标页面进行对数据的各种操作

下面是自己写的一个小例子:

思路是这样的,在Home页面设置一个按钮,点击之后能跳转到User页面并展示一些User页面一开始没有的东西

在路由文件中配置相关路由,

// vue2
// /router/index.js
const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/Home.vue')
  },
  {...},
  {...},
  {
    path: '/user',
    name: 'User',
    component: () => import('../views/User.vue')
  }
]

在Home.vue中配置按钮和点击事件

<!-- vue2 Home.vue -->
<template>
  <div>
    <button @click="userClick">User按钮</button>  
  </div>
</template>
<script>
  export default {
    name: 'Home',
    methods: {
      userClick(){
        this.$router.push({name:'User',params:{a:'aaa',b:'bbb',c:'ccc'}})
      }
    }
  }
</script>

在User.vue中进行对传入参数的处理

<!-- vue2 User.vue -->
<template>
  <h2>我是User标题</h2>
  <p>我是User内容</p>
  <div>
    <p>{{this.$route.params.a}}</p>
    <p>{{this.$route.params.b}}</p>
    <p>{{this.$route.params.c}}</p>
  </div>
</template>
<script>
  export default {
    name: 'User'
  }
</script>

运行结果如下:
运行效果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值