navigateTo 无法在插件中工作 - nuxt 3

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

问题简而言之:

navigateTo
defineNuxtRouteMiddleware
中有效,但在
defineNuxtPlugin
中不起作用。我不想只在或进入网站的每个页面上运行此代码

export default defineNuxtPlugin(nuxtApp => {
  // This data is variable depending on the user who is currently logged in, but for simplicity I will use a fixed object
  const user = {
    isTestUser : true
  };
  
  if(user.isTestUser) {
    return navigateTo("/test");
  }
});

返回时也出现错误

navigateTo
:

Argument of type '(nuxtApp: _NuxtApp) => false | void | RouteLocationRaw | Promise<false | void | NavigationFailure>' is not assignable to parameter of type 'Plugin<Record<string, unknown>> | ObjectPlugin<Record<string, unknown>>'.
  Type '(nuxtApp: _NuxtApp) => false | void | RouteLocationRaw | Promise<false | void | NavigationFailure>' is not assignable to type 'Plugin<Record<string, unknown>>'.
    Type 'false | void | RouteLocationRaw | Promise<false | void | NavigationFailure>' is not assignable to type 'void | Promise<void> | Promise<{ provide?: Record<string, unknown> | undefined; }> | { provide?: Record<string, unknown> | undefined; }'.
      Type 'string' is not assignable to type 'void | Promise<void> | Promise<{ provide?: Record<string, unknown> | undefined; }> | { provide?: Record<string, unknown> | undefined; }'

nuxt.config.ts

ssr: false
nuxt.js nuxtjs3 nuxt3
1个回答
0
投票

有一个解决方案,但我不认为它是最好的。可能有比这更好的东西..但供您参考,我在

ssr:fasle
中使用
nuxt.config.ts
。该文件也适用于客户端 (
test.client.ts
)。

export default defineNuxtPlugin((nuxtApp) => {

  const route = useRoute();
  const user = {
    isTestUser: true,
  };

  // For example, you can verify in other ways, but for simplicity, for example: route.path !== '/test'
  if (user.isTestUser && route.path !== '/test' ) {  
   window.location.href = "/test"; // <===
  }
});

!!重要!!

确保当前页面或当前

route
不等于您想要的页面,因为如果它位于登陆页面或预期的
route
上,则不需要重定向。

© www.soinside.com 2019 - 2024. All rights reserved.