当数据加载到vue中需要时间时,数据无法进入不同的子组件

i1icjdpr  于 2023-10-23  发布在  Vue.js
关注(0)|答案(2)|浏览(152)

“我是新来的,在这里遇到了问题。我的顶级父是下面提到的这个页面代码,有2个子组件。就像{CURRENT PAGE..} > {FancyButton} > {AnotherViewChild}我想使用provide和inject将值从当前父组件传递到孙子组件AnotherViewChild组件,这可以通过以下代码实现,没有问题。但是如果我使用setTimeOut来延迟获取消息,我会得到[]值。
我如何才能得到解决这个问题?通常情况下,当大量数据来自后端时,可能会发生这种情况。我的演示消息数据就像... message.value = [{id:1,name:“ddl”},{id:2,name:“Omen ser”},{id:3、名称:“天然海”},.]`

<script setup lang="ts">
import { ref, provide, computed, onMounted } from 'vue'
import FancyButton from './FancyButton.vue'
let someValue: any[]
  const message = ref<any[]>([])
  
  message.value = [
      {id: 1, name: "ddl"},
      {id: 2, name: "Omen ser"},
      {id: 3, name: "natural sea"},
      {id: 4, name: "Whale is swiming"},
      {id: 5, name: "Best food in"},
      {id: 6, name: "Better choice"},
      {id: 7, name: "What is next?"},
      {id: 8, name: "Other Option"},
    ]
  
  someValue = []
  onMounted(() => {
    setTimeout(() => {
    message.value = [
      {id: 1, name: "ddl"},
      {id: 2, name: "Omen ser"},
      {id: 3, name: "natural sea"},
      {id: 4, name: "Whale is swiming"},
      {id: 5, name: "Best food in"},
      {id: 6, name: "Better choice"},
      {id: 7, name: "What is next?"},
      {id: 8, name: "Other Option"},
    ]
  }, 2000)
  })
  
  
  console.log('-------->', message.value)
  provide('message', message.value)
  

computed(() => {
  console.log('-------->', someValue)
})

</script>

<template>
  <div style="border: 1px solid purple">
    <!-- <h1>Hello</h1>
    <h2 style="color: red">{{ count }}</h2>
    <button @click="addButton" style="color: red">Add</button> -->
    
    <FancyButton>
       <AnotherViewChild />
      <div class="role">Role</div>
      <div class="role">Role</div>
    </FancyButton>
  </div>

</template>

<style scoped>
.role {
  color:green
}
.read-the-docs {
  color: #888;
}
</style>

I am expecting if I use settimeout, data should be available after mentioned timeframe in message.value and can show in my child component <AnotherViewChild /> using provide, inject. Please help.Expected screenshot

fnatzsnv

fnatzsnv1#

如果我理解正确,你的目标是在父组件和孙组件之间延迟数据,我会这样做:

onMounted(() => {
  message.value = [
  {id: 1, name: "ddl"},
  {id: 2, name: "Omen ser"},
  {id: 3, name: "natural sea"},
  {id: 4, name: "Whale is swiming"},
  {id: 5, name: "Best food in"},
  {id: 6, name: "Better choice"},
  {id: 7, name: "What is next?"},
  {id: 8, name: "Other Option"},
];
  setTimeout(() => {
    provide('message', message.value)
   }, 2000);

});

因为如果你在一个setString中赋值message.value,provide()函数将在message.value被赋值之前被调用。换句话说,当你的组件挂载时:

  1. prove()将通过message.value = []调用;
    1.在调用provide()之后,message.value将在2秒后被赋值
z9ju0rcb

z9ju0rcb2#

通过将provide()放置在根目录中并使用'message' provide('message',message)// deleted .value解决了问题

相关问题