Vue-Route传递参数

一,params方式
使用params方式传递参数就是通过拼接参数的形式传递参数。

例传递用户名为张三,获取相应的界面

<template>
  <div id="app">
    <!-- tag可以设置组价的样式。默认为a标签 repalce可以禁用页面返回和前进 -->
  //在此处拼接userId的值为zhangsan,通过v-bind属性拼接
    <router-link :to="'/user/'+userId" tag="button" replace="">user</router-link>
    <router-view></router-view>
  </div>
</template>

<script> 

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

<style>



</style>

import VueRouter from 'vue-router';
import Vue from 'vue';

//路由懒加载方式,在用到对应的模块时才会执行导入
const user = () =>
    import ('../components/user');

//通过Vue.use(插件),安装插件
Vue.use(VueRouter)

//创建VueRouter对象
const routes = [{
        path: '',
        //重定向设置,默认显示的hash为user
        redirect: '/user'
    },
    {
    //当接受到传递过来的参数后调用user组件
        path: '/user/:userId',
        component: user
    }
]
const router = new VueRouter({
    //配置路由和组件之间的对应关系
    routes,
    //可以将默认的hash值改为history值
    mode: 'history'
})

export default router;
<template>
  <div>
      <h2>user</h2>
      <p>user.text</p>
      <h2>{{userId}}</h2>
  </div>
</template>

<script>
export default {
name:'user',
computed:{
    userId(){
        //route属性是指在index.js中定义的routes里处于活跃状态的哪一个route
        //params.userId是因为 path:'/user/:userId'
        return this.$route.params.userId
    }
}
}
</script>

<style>

</style>

二,query方式

query方式传递参数不同于parmas方式拼接,而是建立一个对象,对象中放入传递的值。

例获取lishi和它的age

<template>
  <div id="app">
    <!-- tag可以设置组价的样式。默认为a标签 repalce可以禁用页面返回和前进 -->
    //创建query属性在其对象中写入要传递的值
    <router-link :to="{path:'/profile',query:{name: 'lishi',age:18}}" tag="button">profile</router-link>
    <router-view></router-view>
  </div>
</template>

<script> 

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

<style>



</style>

import VueRouter from 'vue-router';
import Vue from 'vue';

const profile = () =>
    import ('../components/profile')

//通过Vue.use(插件),安装插件
Vue.use(VueRouter)

//创建VueRouter对象
const routes = [
    {
        path: '/profile',
        component: profile
    }
]
const router = new VueRouter({
    //配置路由和组件之间的对应关系
    routes,
    //可以将默认的hash值改为history值
    mode: 'history'
})

export default router;
<template>
  <div>
      <h2>profile 组件</h2>
      <h2>{{message.name}}</h2>
      <h2>{{message.age}}</h2>
  </div>
</template>

<script>
export default {
name:"profile",
computed:{
    message(){
    //获取传递到route中的query对象
        return this.$route.query;
    }
}
}
</script>

<style>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值