saowu's Blog

Vue3路由及传参

Vue3路由及传参
2022-12-14 · 2 min read
Vue 前端 日记

vue3 中的传参方式和vue2中一样,都可以用query和params传参。
不过注意的是,vue2 中是有this的,但是vue3是在setup中进行的,且要引入 useRoute 和useRouter。

一、name+query传参

传递的参数会显示在path上,页面刷新时数据不丢失。如下

http://localhost:3000/details?id=1
  • 传入
<script setup>
import {useRouter} from "vue-router"

const $router = useRouter()

let query = () => {
  $router.push({
    name: "Details",
    query: {id: 1},
  });
}

</script>
  • 接收
<script setup>
import {useRoute} from "vue-router";

const query = useRoute().query;
console.log(query)

</script>

二、path传参

传递的参数会显示到path中,页面刷新时数据不会丢失。如下

http://localhost:3000/details/1
  • 传入
//路由配置
{
    path: '/details/:id',
    component: () => import('@/views/details'),
}
<script setup>
import {useRouter} from "vue-router"

const $router = useRouter()

let params = () => {
  $router.push(`/details/${id}`);
}

</script>
  • 接收
<script setup>
import {useRoute} from "vue-router";

const params = useRoute().params;
console.log(params)

</script>

三、path+params传参

传递的参数不会显示在path上,页面刷新时数据会丢失

  • 传入
//路由配置
{
    path: '/details',
    component: () => import('@/views/details'),
}
<script setup>
import {useRouter} from "vue-router"

const $router = useRouter()

let params = () => {
  $router.push({
    path: "/details",
    params: {id: 1},
  });
}

</script>
  • 接收
<script setup>
import {useRoute} from "vue-router";

const params = useRoute().params;
console.log(params)

</script>

参考文章 父子组件传参

Copyright © 2020 - 2024 saowu. All Right Reserved
Powered by Gridea