vue-router参数传递

参数传递方法:

    params的类型
        1.配置路由格式 /router/:id
        2.传递的方式:在path后面跟上对应的值
        3.传递后形成的路径:/router/123
    query的类型
        1.配置路由格式:/router,普通的配置
        2.传递的方式:query的key作为传递的方式
        3.传递后形成的路径:/router?id=123

params传递:

1.在index.js配置路由

 {
    path: '/user/:userid',
    component: User
 }

2.在App.vue中配置路径

<template>
  <div id="app">
    <router-link v-bind:to='"/user/"+userid'>用户页面</router-link>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'App',
  data(){
    return {
      userid:'hhhh'
    }
  },
}
</script>

<style>

</style>

3.在User.vue获取参数

<template>
  <div>
      <h2>用户页面</h2>
      <!-- $route 是处于活跃状态的路由 -->
      <h2>{{$route.params.userid}}</h2>
  </div>
</template>

4.效果图

query传递

1.在index.js配置路由

{
    path: "/profile",
    component: Profile
}

2.在App.vue中配置路径

<template>
  <div id="app">
    <router-link :to='{path:"/profile",query:{name:"xh",age:18,sex:"boy"}}'>档案资料</router-link>

    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'App',
}
</script>

<style>

</style>

3.在Profile.vue获取参数

<template>
  <div>
      <h2>用户档案资料</h2>
      <h4>{{$route.query.name}}</h4>
      <h4>{{$route.query.age}}</h4>
      <h4>{{$route.query.sex}}</h4>
  </div>
</template>

4.效果图

通过原生js的方法实现router-link

<template>
  <div id="app">
    <h2>hello world</h2>
    
    <button @click='homeClick'>home</button>
    <button @click='aboutClick'>about</button> 
    <button @click='userClick'>用户页面</button>
    <button @click='profileClick'>用户档案</button>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'App',
  data(){
    return {
      userid:'hhhh'
    }
  },
  methods:{
    homeClick(){
      // 通过代码的方式修改路由  $router是new的router对象
      this.$router.push('/home')
      // this.$router.replace('/home')
    },
    aboutClick(){
      this.$router.push('/about')
      // this.$router.replace('/about')

    },
    userClick(){
      this.$router.push('/user/' + this.userid)
    },
    profileClick(){
      this.$router.push({
        path:'/profile',
        query:{
          name:'lh',
          age:22,
          sex:"girl"
        }
      })
    }
  }
}
</script>

<style>

</style>

$router是new的router对象

$route 是处于活跃状态的路由

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值