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

zbdgwd5y  于 5个月前  发布在  Java
关注(0)|答案(1)|浏览(47)

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

<template>
  <div class="p-4 flex ">

    <div>
        <img :src="author.profileImage" alt="" class="w-10 h-10 rounded-full" />

    </div>

    <div class="ml-3">
        <span class="font-medium text-gray-800 dark:text-white"> {{author.name}}</span>


        <span class="ml-3 text-sm font-medium text-gray-400">
            <NuxtLink to="#">
                {{ author.handle }}
            </NuxtLink>

            . {{ props.tweet.postedAtHuman }}
        </span>

        <p v-if="props.tweet.replyTo" class="text-sm">

          <span class="text-gray-500">
            Replying to 
          </span> 
            <span  @click="doSomething(replyToTweetUrl)" class="text-blue-400">
                {{ props.tweet.replyTo.author.handle }}
            </span>
        </p>
       
    </div>
  </div>
</template>

<script setup>
const props = defineProps({
  tweet: {
    type: Object,
    required: true,
  },
});

const author = props.tweet.author;
const { setTweetIdUrl ,tweetIdUrl } = useUrls();
  console.log(props.tweet.replyTo?.id)

const replyToTweetUrl = computed(() => `/status/${props.tweet.replyTo?.id}`)

const router = useRouter();

async function doSomething(replyToTweetUrl) {

  console.log("ldsùfez  "+tweetIdUrl.value)
  tweetIdUrl.value = replyToTweetUrl
  console.log("ldsùfez 2  "+tweetIdUrl.value)

  await router.push(replyToTweetUrl);

}

</script>

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

<template>
  <div>
    <MainSection title="Tweet" :loading="loading">
      <Head>
        <Title> </Title>
      </Head>
      <TweetDetails :user="user" :tweet="tweet"/>
    </MainSection>

   
  </div>
</template>

<script setup>
const loading = ref(false);
const { getTweetById } = useTweets();
const tweet = ref(null);

async function getTweet() {
  loading.value = true;
  try {
      // Use nextTick to ensure the DOM is updated
      await nextTick();

    //const response = await getTweetById(getTweetIdFromRoute());

    const tweetId = useRoute().params.id;
    const response = await getTweetById(tweetId);
    tweet.value = response.tweet;
    console.log(response);
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
}

const {useAuthUser} = useAuth()
const user = useAuthUser()

onBeforeMount(() => {
  getTweet();
});
</script>


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

sqyvllje

sqyvllje1#

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

<script setup>
const tweetId = useRoute().params.id;

async function getTweet() { 
// can use tweetId here
...
}

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

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


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

相关问题