vue路由跳转携带参数

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vue路由跳转携带参数

糖糖246   2022-10-20 我要评论

一、<router-link> 方式跳转

1. 携带query参数

 <router-link to="/detail?id=001&title=消息001"> 消息001</router-link>
<router-link :to="{
        name: 'detail',
        path: '/detail', 
        query: {
                id: '001',
                title: '消息001'
        }
}"

注:此种方式不需要动路由配置,to属性对象形式中name和path二选一即可 。

此时浏览器地址栏地址为:http://localhost:8080/detail?id=001&title=消息001 

接收参数为:

$route.query.xxx

2. 携带params参数 

<router-link :to="`/detail/${id}/${title}`"> {{ title }} </router-link> 
<router-link :to="{
        name: 'detail',
        path: '/detail',
        params: {
                id: '001',
                title: '消息001'
        }
}"

注意:此种方式需要修改路由配置,且to的对象形式中只能用name匹配路由

{
       name: 'detail',
        path: '/detail/:id/:title'
        component: Detail
} 

此时浏览器地址栏地址为:http://localhost:8080/detail/001/消息001 

接收参数为:

$route.params.xxx

3.将参数转换为props属性

我们可以通过配置路由时的props属性,将params/query携带的参数,在组件中用props属性来接收,这样用时可以直接使用,就不需要$route.params.xxx/$route.query.xxx的形式了

配置方式:

{
    name:'detail',
    path:'/detail',
    component: Detail,
 
    /**
    方式一,值为对象,对象中的key-value会以props的形式传递给Detail组件,
    但是传递的值都是一样的,不推荐
    props: {
         id: '123',
         title: '消息001',
    },
    **/
 
    /**
    方式二,值为布尔值,若布尔值为真,就会把该组件收到的所有params参数,以props的形式传式传递给Detail组件, 但之这种方式只适用于params参数
    props: true,
    **/
 
    /**
    方式三,值为函数,内置传参$route,可以使用结构赋值形式
    **/
    props({query}){
        return {id: query.id, title: query.title}
    },

还学到了一种结构再结构的形式

props({ query: { id, title } }) {
        return { id, title }

二、编程方式跳转路由

通过编写代码的方式使路由发生跳转,跳转方式有两种,一种是push,一种是replace,他们都是$router上的函数(存在于VueRouter原型上)。此时携带参数方式为:

this.$router.push({
    name:  'detail',
    params: {
        id: xxx,
        title: xxx
    },
    /**
    query: {
        id: xxx,
        title: xxx
    }
    **/
})
 
this.$router.replace({
    name:  'detail',
    params: {
        id: xxx,
        title: xxx
    },
    /**
    query: {
        id: xxx,
        title: xxx
    }
    **/
})          

注意:不论何种方式跳转,想要在标签中接收到不同的params就需要在路由配置时用/:占位,不然只能接收到第一次打开时带过来的参数。

总结

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们