如何访问 Vue 3 功能组件中的路由器?

问题描述 投票:0回答:3

我想添加一个简单的功能组件,它将用随机数据预填充我的 Pinia 商店并路由回主页。我试过

useRouter
但值未定义。

import { FunctionalComponent } from "vue";
import { useRouter } from "vue-router";
import { useUserProfileStore } from "./stores/UserProfile";

const Prefill: FunctionalComponent<{}> = (props, { slots, emit, attrs }) => {
  const userProfileStore = useUserProfileStore();
  const router = useRouter();
  userProfileStore.randomData();
  router.replace("/"); // but router is undefined?
};
Prefill.props = [];
Prefill.emits = [];
export default Prefill;

我把我的路线定义为

    {
      path: "/cheat",
      name: "Prefill",
      component: Prefill,
    },
vue.js vue-router
3个回答
0
投票

看来您正在尝试在功能组件中使用

useRouter
钩子。您可以使用
inject
函数将路由器实例注入到您的组件中。这是一个例子:

import { FunctionalComponent, inject } from "vue";
import { useUserProfileStore } from "./stores/UserProfile";

const Prefill: FunctionalComponent<{}> = (props, { slots, emit, attrs }) => {
  const userProfileStore = useUserProfileStore();
  const router = inject("$router");
  userProfileStore.randomData();
  router.replace("/"); // should work now
};
Prefill.props = [];
Prefill.emits = [];
export default Prefill;

希望对您有所帮助!


0
投票

类似于 Mehdi 的回答,但我使用的不是

inject("$router")
实际的路由器实例。

Mehdi 的回答是类型检查失败。

import { FunctionalComponent } from "vue";
import { router } from "./router";
import { useUserProfileStore } from "./stores/UserProfile";

const Prefill: FunctionalComponent = () => {
  const userProfileStore = useUserProfileStore();
  userProfileStore.randomData();
  router.replace("/");
};
Prefill.props = [];
Prefill.emits = [];
export default Prefill;

0
投票

功能组件是无状态的,不会产生任何副作用,但它们可以通过与组件元素交互来触发事件:

import { FunctionalComponent } from "vue";

const Prefill: FunctionalComponent<{}> = (props, { slots, emit, attrs }) => {
 
//somewhere in the render function/jsx do
  emit('goto','/')
 
};
Prefill.props = [];
Prefill.emits = ["goto"];
export default Prefill;

在父组件中:

<Prefill @goto="(path)=>$router.push(path)" .../>
© www.soinside.com 2019 - 2024. All rights reserved.