在 onMounted 中使用路由器时应用程序没有响应

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

我想根据组件中可组合项的状态重定向页面。但由于某种原因,在 onMounted 中添加路由器会挂起应用程序。

这是我的组件代码:

const { notes, error, loading } = useNotes();
const router = useRouter();

onMounted(async () => {
  if (error) {
    await router.push("/");
  }
});
</script>

<template>
  <p v-if="loading">Loading...</p>
  <pre v-else>
    {{ notes }}
  </pre>
</template>

这是我的可组合代码:

export function useNotes() {
  const notes = ref();
  const error = ref(null);
  const loading = ref(false);
  onMounted(async () => {
    loading.value = true;
    try {
      notes.value = await useFetch("https://jsonplaceholder.typicode.com/todos/1");
    } catch (e) {
      error.value = e as any;
    }
    loading.value = false;
  });

  return { notes, loading, error };
}

我什至尝试在 onMounted 中使用 router.ready() 但应用程序仍然没有响应。

如果我将路由器推送移到可组合项中,它会起作用,但这是一个黑客修复,因为我不想将组件逻辑放入可组合项中

vue.js vuejs3 vue-component vue-router vue-composition-api
1个回答
0
投票

我找到的修复方法是将路由器重定向放入观察程序中。想知道还有没有其他办法

更新了组件代码:

const { notes, error, loading } = useNotes();
const router = useRouter();

watch((error) => error && router.push("/"));
</script>

<template>
  <p v-if="loading">Loading...</p>
  <pre v-else>
    {{ notes }}
  </pre>
</template>
© www.soinside.com 2019 - 2024. All rights reserved.