vue3路由useRoute和useRouter区别,vue3 useRouter(跳转), useRoute(获取路由参数) 的区别。
useRouter跳转传参
import { useRouter } from 'vue-router' ---- const router = useRouter() router.push({ path:"/counter", query:{ userId:"123" } })
useRoute接参数
//counter中接 import {useRoute} from "vue-router" ---- const route = useRoute(); console.log("route",route.query);
通过useRouter传参的三种方式
import { useRouter } from 'vue-router' export default { setup() { const userRouter = useRouter() userRouter.push({ name: 'Home', params: { name: 'dx', age: 18 } }) } }
请注意params只与name搭配生效,name就是route配置时的name
const routes: Array<RouteRecordRaw> = [ { path: '/', name: 'Home', component: Home } ]
通过useRoute来接收params参数
import { useRoute } from 'vue-router' export default { setup() { const route = useRoute() console.log(route.params) } }
显式传参query
import { useRouter } from 'vue-router' export default { setup() { const userRouter = useRouter() userRouter.push({ path: '/', query: { name: 'dx', age: 18 } }) } }
path与query是一对,name和params是一对,请别混用。通过useRoute来接收query参数
import { useRoute } from 'vue-router' export default { setup() { const route = useRoute() console.log(route.query) } }
除了他们的传递和接收方式不同外
显式query会很明显的跟在新的url上,而隐式params不会
隐式params在刷新后可能会消失,我们可以在它存在的时候存如缓存中,如localstorage
隐式params比显式query相对而言更安全,不会将参数直接暴露给用户