赞
踩
路由跳转并传递参数的应用十分广泛,以下是一些常见的应用场景:
本文主要介绍在Vue3工程(使用 setup 语法)中如何进行路由跳转并传递参数
在src/router/index.js
文件中编写路由规则
import {createRouter, createWebHistory} from 'vue-router' import HomeView from '@/views/HomeView.vue' const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes: [ { path: '/', name: 'homeView', component: HomeView }, { path: '/sourceView', name: 'sourceView', component: () => import('@/views/SourceView.vue') }, { path: '/targetView', name: 'targetView', component: () => import('@/views/TargetView.vue') } ] }) export default router
src/views/SourceView.vue
<template>
<div>
<h1>源页面</h1>
</div>
</template>
<script setup>
</script>
<style scoped>
</style>
src/views/TargetView.vue
<template>
<div>
<h1>目标页面</h1>
</div>
</template>
<script setup>
</script>
<style scoped>
</style>
在路径后面添加需要传递的参数,如果需要传递多个参数,多个参数之间用&
符号隔开
template部分(to属性前面记得加上:
)
<router-link :to="`/targetView?username=${username}&gender=${gender}`">跳转到目标页面</router-link>
script部分
const username = ref('zhangsan')
const gender = ref(1)
template部分
<button @click="jumpToTargetView">跳转到目标页面</button>
script部分
import router from '@/router/index.js'
import {ref} from 'vue'
const username = ref('zhangsan')
const gender = ref(1)
const jumpToTargetView = () => {
router.push({
path: '/targetView',
query: {
username: username.value,
gender: gender.value
}
})
}
template部分
用户名:{{ username }}
<hr>
性别:{{ gender }}
script部分(在onMounted钩子函数中编写接收参数的代码)
import {onMounted, ref} from 'vue'
import {useRoute} from 'vue-router'
const route = useRoute()
const username = ref('')
const gender = ref(1) // 1男 2女
onMounted(() => {
username.value = route.query.username
gender.value = route.query.gender
})
src/views/SourceView.vue
<template> <div> <h1>源页面</h1> <!--通过router-link标签跳转--> <router-link :to="`/targetView?username=${username}&gender=${gender}`">跳转到目标页面</router-link> <!--通过js代码跳转--> <button @click="jumpToTargetView">跳转到目标页面</button> </div> </template> <script setup> import router from '@/router/index.js' import {ref} from 'vue' const username = ref('zhangsan') const gender = ref(1) const jumpToTargetView = () => { router.push({ path: '/targetView', query: { username: username.value, gender: gender.value } }) } </script> <style scoped> </style>
src/views/TargetView.vue
<template> <div> <h1>目标页面</h1> 用户名:{{ username }} <hr> 性别:{{ gender }} </div> </template> <script setup> import {onMounted, ref} from 'vue' import {useRoute} from 'vue-router' const route = useRoute() const username = ref('') const gender = ref(1) // 1男 2女 onMounted(() => { username.value = route.query.username gender.value = route.query.gender }) </script> <style scoped> </style>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。