javascript useRoute().params在初始加载时为空,但在刷新后工作

zbdgwd5y  于 2024-01-05  发布在  Java
关注(0)|答案(1)|浏览(123)

组件#1:包含一个click函数,它在路由中推送新的id,如下所示:

  1. <template>
  2. <div class="p-4 flex ">
  3. <div>
  4. <img :src="author.profileImage" alt="" class="w-10 h-10 rounded-full" />
  5. </div>
  6. <div class="ml-3">
  7. <span class="font-medium text-gray-800 dark:text-white"> {{author.name}}</span>
  8. <span class="ml-3 text-sm font-medium text-gray-400">
  9. <NuxtLink to="#">
  10. {{ author.handle }}
  11. </NuxtLink>
  12. . {{ props.tweet.postedAtHuman }}
  13. </span>
  14. <p v-if="props.tweet.replyTo" class="text-sm">
  15. <span class="text-gray-500">
  16. Replying to
  17. </span>
  18. <span @click="doSomething(replyToTweetUrl)" class="text-blue-400">
  19. {{ props.tweet.replyTo.author.handle }}
  20. </span>
  21. </p>
  22. </div>
  23. </div>
  24. </template>
  25. <script setup>
  26. const props = defineProps({
  27. tweet: {
  28. type: Object,
  29. required: true,
  30. },
  31. });
  32. const author = props.tweet.author;
  33. const { setTweetIdUrl ,tweetIdUrl } = useUrls();
  34. console.log(props.tweet.replyTo?.id)
  35. const replyToTweetUrl = computed(() => `/status/${props.tweet.replyTo?.id}`)
  36. const router = useRouter();
  37. async function doSomething(replyToTweetUrl) {
  38. console.log("ldsùfez "+tweetIdUrl.value)
  39. tweetIdUrl.value = replyToTweetUrl
  40. console.log("ldsùfez 2 "+tweetIdUrl.value)
  41. await router.push(replyToTweetUrl);
  42. }
  43. </script>

字符串
组件#2是status/[id].vue

  1. <template>
  2. <div>
  3. <MainSection title="Tweet" :loading="loading">
  4. <Head>
  5. <Title> </Title>
  6. </Head>
  7. <TweetDetails :user="user" :tweet="tweet"/>
  8. </MainSection>
  9. </div>
  10. </template>
  11. <script setup>
  12. const loading = ref(false);
  13. const { getTweetById } = useTweets();
  14. const tweet = ref(null);
  15. async function getTweet() {
  16. loading.value = true;
  17. try {
  18. // Use nextTick to ensure the DOM is updated
  19. await nextTick();
  20. //const response = await getTweetById(getTweetIdFromRoute());
  21. const tweetId = useRoute().params.id;
  22. const response = await getTweetById(tweetId);
  23. tweet.value = response.tweet;
  24. console.log(response);
  25. } catch (error) {
  26. console.log(error);
  27. } finally {
  28. loading.value = false;
  29. }
  30. }
  31. const {useAuthUser} = useAuth()
  32. const user = useAuthUser()
  33. onBeforeMount(() => {
  34. getTweet();
  35. });
  36. </script>


我需要在点击链接到该路由后立即从路由中获取ID,但相反,它在第一次加载时返回一个空对象(整个useRoute是空的),除非我手动刷新页面,任何想法可能是什么问题?请帮助!

sqyvllje

sqyvllje1#

useRoute只能在设置上下文中使用(即组件的创建钩子)。

  1. <script setup>
  2. const tweetId = useRoute().params.id;
  3. async function getTweet() {
  4. // can use tweetId here
  5. ...
  6. }

字符串
另外,如果你使用这样的代码,还有一个比onBeforeMounted更好的生命周期挂钩:

  1. // Use nextTick to ensure the DOM is updated
  2. await nextTick();


您基本上是在等待mounted钩子的出现,这是在DOM呈现之后出现的钩子。

展开查看全部

相关问题