【问题标题】:Properly accesing to reactive array in Vue 3正确访问 Vue 3 中的反应式数组
【发布时间】:2021-07-24 19:00:33
【问题描述】:

我正在开发我的 Vue 3 应用程序,但在按预期工作时遇到了一些麻烦。

我需要的是正确访问反应式数组。让我向您展示代码以进行澄清:

我有一个全球商店store/questions/index.js,代码如下:


const useQuestionsAndAnswers = () => {
    const data = reactive([])
    const getQuestionsAndAnswers = async () => {
      const response = await fetch('../../../db/questions.json')
      const fetchedData = await response.json();
      if(response.status === 200) {
        fetchedData.data.forEach(obj => data.push(obj))
        console.log(data[0]);  <--------- // This console.log works ok
      } else {
        console.log('Something went wrong')
      }
    };
      
    onMounted(() => {
        getQuestionsAndAnswers();
    });

    return { data }
}

export default useQuestionsAndAnswers;

如果我运行console.log(data[0]),我会得到我期望的对象。所以假设它工作正常。

您可能已经意识到,我希望将这些数据用于某些 Vue 组件。好吧,组件是下一个:

components/calculator/Questions.vue:

<template>
  <div class="block max-w-4xl" v-if='data'>
    <h3 class='py-4'>Seleccioná la opción que mejor te describa</h3>
    {{ data[0] }} // Same as the console.log I showed you before.
  </div>
</template>

<script>
import useQuestionsAndAnswers from '../../store/questions/index.js'
export default {
  setup() {
    const  { data }  = useQuestionsAndAnswers();

    console.log(data)

    return {
      data,
    }
  }
}
</script>

这就是事情变得奇怪的部分。 DOM {{ data[0] }} 中的绑定数据运行良好,并显示与该位置相对应的整个对象,但如果我尝试以 data[0].question 访问 question 键,它会显示数据,但如果我刷新页面,我会得到未定义。好像我缺少反应性。

另一个问题发生在我的setup() 函数内部。如果我console.log(data) 我得到预期的Proxy 和我的array。但是,如果我尝试访问提到的数组中的一个对象console.log(data[0]),我又得到了undefined

最后,我将向您展示我收到的 json 的示例:

{
    "data": [
        {
            "question" : "Estás en medio de una pandemia mundial y estatizas una conocida empresa de alimentos (su nombre empieza con V de Vicentín) que no le paga a sus acreedores hace años. Qué harías ante el embate de Clarín?",
            "image": "@/assets/alberto.png",
            "id": 1,
            "answers": [
                {
                    "id": 1,
                    "answer": "Me haría el picante unos días y después me tiraría atrás.",
                    "points": 2,
                    "slug": "haria-el-picante"
                }
            ]
        }
    ]
}

所以我想要的是正确访问数组并显示我想要的数据。

提前致谢!

【问题讨论】:

标签: javascript arrays vue.js vuejs3


【解决方案1】:

如果有人遇到同样的情况,我会告诉你解决方案是如此简单:

对于v-if='data',我以为我在检查数组是否确实存在,但您可能知道 Vue 3 在处理对象时与 Proxy 一起使用,所以我实际上是在检查该对象是否存在。

在这种情况下,解决方案只需在我的句子中添加lengthv-if='data.length &gt; 0'解决了整个问题。在我的setup() 函数中也是如此,以防您需要在&lt;script&gt; 中使用您的数组。

就是这样。

【讨论】:

    猜你喜欢
    • 2021-02-11
    • 1970-01-01
    • 2022-11-29
    • 2021-10-05
    • 1970-01-01
    • 2018-12-08
    • 2020-05-26
    • 1970-01-01
    • 2020-05-28
    相关资源
    最近更新 更多