如何在Vue 3 Functional组件中访问路由器?

frebpwbc  于 2023-03-24  发布在  Vue.js
关注(0)|答案(3)|浏览(161)

我想添加一个简单的功能组件,它将用随机数据预填充我的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,
    },
qjp7pelc

qjp7pelc1#

看起来你是想在一个功能组件中使用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;

希望这能有所帮助!

ubbxdtey

ubbxdtey2#

与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;
w8ntj3qf

w8ntj3qf3#

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

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)" .../>

相关问题