Vue 路由传参

URL传参

路由配置
在这里插入图片描述
文件结构
在这里插入图片描述

动态路由匹配

一个“路径参数”使用冒号 : 标记。当匹配到一个路由时,参数值会被设置到 this.$route.params,可以在每个组件内使用。
test1 跳转至 test2

test1.vue
在这里插入图片描述

<template>
    <div>
        <h1>test1</h1>
        <router-link :to="'/test/test2/'+id">go test2</router-link>
        <button @click="go()">go test2</button>
    </div>
</template>

<script>
export default {
    data() {
        return {
            id: 106
        }
    },
    methods: {
        go(){
            this.$router.push({ path: `/test/test2/${this.id}` })
        }
    },
}
</script>

test2.vue
在这里插入图片描述

<template>
    <div><h1>test2</h1>
    <h2>ID:{{ this.$route.params.id }}</h2></div>
</template>
<script>
export default {
    data() {
        return {
            id: this.$route.params.id
        }
    },
    mounted() {
        this.log()
    },
    methods: {
        log(){
            console.log(this.id);
        }
    },
}
</script>

带查询参数的URL传参

test3 跳转至 test4

test3.vue
在这里插入图片描述

<template>
    <div>
        <h1>test3</h1>
        <router-link :to="{path: '/test/test4', query: {id: user.id, class: user.class }}">go test4</router-link>
        <button @click="go()">go test4</button>
    </div>
</template>

<script>
export default {
    data() {
        return {
            user: {
                id:106,
                class: 102
            }
        }
    },
    methods: {
        go(){
            this.$router.push({path: '/test/test4', query: {id: this.user.id, class: this.user.class }})
        }
    },
}
</script>

test4.vue
在这里插入图片描述

<template>
    <div>
        <h1>test4</h1>
        <h2>ID:{{ this.$route.query.id }}</h2>
        <h2>Class:{{ this.$route.query.class }}</h2>
        <h3><pre>{{ user }}</pre></h3>
    </div>
</template>
<script>
export default {
    data() {
        return {
            user: {
                id: this.$route.query.id,
                class: this.$route.query.class
            }
        }
    },
    mounted() {
        this.log()
    },
    methods: {
        log(){
            console.log(this.user);
        }
    },
}
</script>

传参是this.$router,接收参数是this.$route
1.$router为VueRouter实例,想要导航到不同URL,则使用$router.push方法
2.$route为当前router跳转对象,里面可以获取name、path、query、params等

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值