Vue 之路由传参

在 vue3.0 里面使用路由必须要引入 useRouter 和 useRoute

import { useRoute, useRouter } from 'vue-router'

秉承谁长谁先死,Router 长 所以他负责跳转,Route 负责接收数据

传参使用query和params,主要区别就是前者使用path进行跳转,后者使用name进行跳转
//使用query
function useHooks() {
  const Router = useRouter() //跳转
  const Route = useRoute() //获取到值
  const Routeid = computed(() => {
    return Route.query.id
  })
  const gotourl = () => {
    console.log('执行了')
    Router.push({
      path: '/about',
      query: {
        id: '6666',
      },
    })
  }
  return {
    gotourl,
    Routeid,
  }
}
//使用params
function useHooks() {
  const Router = useRouter() //跳转
  const Route = useRoute() //获取到值
  const Routename = computed(() => {
    return Route.params.id
  })
  const gotourl = () => {
    console.log('执行了')
    Router.push({
      name: 'about',
      params: {
        id: '6666',
      },
    })
  }
  return {
    gotourl,
    Routename ,
  }
}

以上这两种方式无需设定路由切换时必须传入参数,相对来说比较灵活,还有一种方式实在注册路由的时候规定必须要传入的参数

{
    path: '/houselist2/:data',
    name: 'houselist2',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/Houselist2.vue')
  }


 const route = useRoute();
    console.log(route.params.data)//注意这里使用的是params
Logo

前往低代码交流专区

更多推荐