情深忆往缠绵 2023-04-07 11:59 采纳率: 44.6%
浏览 59
已结题

如何在外面拿到onmounted中定义的值

代码
<template>
  <div>
    <!--    <h1>购物车管理页面</h1>-->
    <!--    <table v-for="(item,index) in list.array">-->
    <!--      <tr>-->
    <!--        <td><input v-model="" type="text"></td>-->
    <!--      </tr>-->
    <!--    </table>-->
    {{ text }}
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'

const list = reactive({ array1: [], array2: [], array3: [], arrayChild: [] })
const text = ref()

onMounted(() => {
  fetch('/4-3/gouwu.json').then(x => x.json()).then(x => {
    list.array1 = x.shu
    list.array2 = x.shiwu
    list.array3 = x.qita
    console.log(list.array1)
  })
})
console.log(list.array1.length)
text.value = list.array1
</script>

<style scoped>

</style>




img

  • 写回答

1条回答 默认 最新

  • H3T 2023-04-07 12:30
    关注

    list.array1 是在异步请求中设置的,当 text computed 属性被设置为 list.array1 时,由于在 onMounted 钩子中的异步请求,list.array1 目前是一个空数组。
    尝试修改:

    <template>
      <div>
        {{ text }}
      </div>
    </template>
     
    <script setup>
    import { onMounted, reactive, computed } from 'vue'
    
    const list = reactive({ array1: [], array2: [], array3: [], arrayChild: [] })
    
    onMounted(() => {
      fetch('/4-3/gouwu.json')
        .then(x => x.json())
        .then(x => {
          list.array1 = x.shu
          list.array2 = x.shiwu
          list.array3 = x.qita
        })
    })
    
    const text = computed(() => {
      return list.array1.length > 0 ? list.array1[0] : ''
    })
    
    </script>
     
    <style scoped>
    </style>
    

     
    如果答案对您有所帮助,望采纳。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 4月14日
  • 已采纳回答 4月11日
  • 修改了问题 4月7日
  • 修改了问题 4月7日
  • 展开全部

悬赏问题

  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因