1.使用编程式导航进行路由的传参
1.1query传参:query传参有一个缺点,就是传递的参数会显示到地址栏中,对于某一些操作,可能会有些许不安全,那么他怎么传参呢,下面我来给大家一一介绍
<template>
<div class="container">
<h1>路由传参</h1>
<!-- 我们简单定义一些数据,做传参使用 -->
<table border style="width:100%">
<thead>
<tr>
<th>id</th>
<th>名字</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="item in list" :key="item.id">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td><button @click="goReceive(item)">路由跳转+传参</button></td>
</tr>
</tbody>
</table>
<router-view></router-view>
</div>
</template>
<script setup>
import { reactive, ref } from 'vue'
//导入vue-router
import { useRouter } from 'vue-router';
const router = useRouter()
const list = reactive([
{id:1, name: '哈哈'},
{id:2, name: '嘿嘿'},
{id:3, name: '嗨嗨'},
])
const goReceive = (item) => {
//直接router.push进行编程式导航
router.push({
path:'/receive',
//这里直接传一个item,item就是一个对象
query:item
//你也可以这样写 二选一
query: {
id:xxxx,
name:'xxxx'
}
})
}
</script>
<style lang="scss" scoped>
</style>
好了,现在我们已经传值了,那么在对应的页面应该如何接收呢,直接上代码
<template>
<div class="container">
<h1>我可以接收</h1>
<ul>
<li>
id:{{route.query.id}} <br>
姓名:{{route.query.name}}
</li>
</ul>
</div>
</template>
<script setup>
import { reactive, ref } from 'vue'
import { useRoute } from 'vue-router';
const route = useRoute()
const getInfo = () => {
//你可以在这里面进行赋值操作,也可以想template里面通过route.query.xxx赋值
console.log(route.query);
}
getInfo()
</script>
<style lang="scss" scoped>
</style>
1.2params传参
params传值:params传值他不会显示到地址栏中,相对于query来说,他的安全系数会高一些。
但是请注意一个问题,params进行编程式导航传参的时候,不能使用path,如果使用了path ,他的参数是传递不过去的。
下面我们就来实战一下吧
<template>
<div class="container">
<h1>路由传参</h1>
<table border style="width:100%">
<thead>
<tr>
<th>id</th>
<th>名字</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="item in list" :key="item.id">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td><button @click="goReceive(item)">路由跳转+传参</button></td>
</tr>
</tbody>
</table>
<router-view></router-view>
</div>
</template>
<script setup>
import { reactive } from 'vue'
import { useRouter } from 'vue-router';
const router = useRouter()
const list = reactive([
{id:1, name: '哈哈'},
{id:2, name: '嘿嘿'},
{id:3, name: '嗨嗨'},
])
const goReceive = (item) => {
router.push({
name:'Receive',
params:item
})
}
</script>
<style lang="scss" scoped>
</style>
接收
<template>
<div class="container">
<h1>我可以接收</h1>
<ul>
<li>
id:{{route.params.id}} <br>
姓名:{{route.params.name}}
</li>
</ul>
</div>
</template>
<script setup>
import { reactive, ref } from 'vue'
import { useRoute } from 'vue-router';
const route = useRoute()
const getInfo = () => {
console.log(route.params);
}
getInfo()
</script>
<style lang="scss" scoped>
</style>