You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue计算属性中如何选取数组的第一个元素?

解决方案

核心问题分析

  1. 错误直接访问ref对象的私有属性_rawValue,Vue3中需通过.value获取ref的实际值;
  2. Firestore数据为异步加载,初始状态Subscribed.value为null,直接取数组元素会触发报错;
  3. 需先确保数组不为空,再访问第一个元素的字段。

修改后的组件代码

<script>
import getCollection from '../Composables/getCollection';
import getUser from '../Composables/getUser';
import { computed } from "vue"
export default {
    props: ['id'],
    setup(props) {
        const { user } = getUser()
        const { documents: Subscribed } = getCollection(
            'Subscribed', 
            ['userId', '==', user.value?.uid] // 用可选链避免用户未加载时的报错
        )

        // 修正后的计算属性
        const Purchased1 = computed(() => {
            // 先校验数据是否存在且有效
            if (!Subscribed.value || !Array.isArray(Subscribed.value) || Subscribed.value.length === 0) {
                return false;
            }
            // 取数组第一个元素判断字段值
            return Subscribed.value[0].Purchased1 === 'Purchased1';
        });

        return { Subscribed, Purchased1, user }
    }
}
</script>

关键修改说明

  • 替换_rawValue为.value:Subscribed是Vue的ref对象,必须通过.value访问内部值,_rawValue为框架私有属性,不建议直接依赖;
  • 增加空值校验:异步加载期间数据未就绪,先判断数组是否存在且非空,避免Cannot read properties of undefined错误;
  • 可选链处理用户ID:user.value?.uid防止用户信息未加载完成时,访问uid触发的报错;
  • 严格相等判断:用===替代==,避免类型转换导致的意外逻辑错误。

额外优化方案

如果业务逻辑确保查询只会返回单个文档,可以修改getCollection直接返回单个对象,简化后续处理:

// 修改getCollection中的onSnapshot回调部分
const unsub = collectionRef.onSnapshot(snap => {
    let result = null;
    snap.docs.forEach(doc => {
        if (doc.data().createdAt) {
            result = {...doc.data(), id: doc.id};
        }
    });
    
    documents.value = result; // 存储单个对象而非数组
    error.value = null
}, err => {
    console.log(err.message)
    documents.value = null
    error.value = 'could not fetch the data'
})

修改后计算属性可简化为:

const Purchased1 = computed(() => Subscribed.value?.Purchased1 === 'Purchased1');

内容的提问来源于stack exchange,提问作者Epimetheus14

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 17:43:16