首页 > 解决方案 > 从导入的 .js 可组合项返回的 Vue3 访问数组

问题描述

setup() {
const { orders, orders_error, load_orders, profits } = getOrders()
load_orders()


console.log('ARRAY', profits)
let new_series = [{
  name: 'series1',
  data: profits.value
}]
return { new_series, orders, load_orders, orders_error, profits }

这是 .js 导出的函数:

import { ref } from 'vue'
import { projectFirestore, projectAuth } from '../firebase/config'
//import { ref } from '@vue/composition-api'

const getOrders  = () => {
    const user = projectAuth.currentUser.uid
    let orders = ref([])
    let profits = ref([])
    let profit = 0
    const orders_error = ref('')
    
    const load_orders = async () => {
        try {

            projectFirestore.collection('users')
                .doc(user)
                .collection('orders')
                .doc('845thfdkdnefnt4grirg')
                .collection('profits')
                .onSnapshot(async (snap) => {
                    // In this implementation we only expect one active or trialing subscription to exist.
                    let docs = snap.docs.map(doc => {
                            return { ...doc.data(), id: doc.id }
                    })
                    orders.value = docs
                    let last = 0

                    orders.value.forEach(element => {
                        console.log('ELEMENT', element.profit_cash)
                        profit = last + element.profit_cash
                        last = profit
                        profits.value.push(profit)
                        //orders.push(element.profit_cash)
                    })
                    //console.log('ARR', profits.value)
                    
                });
            
        }
        catch (err) {
            orders_error.value = err.message
            console.log(orders_error.value)
        }
    }
    load_errors()

    return { orders, orders_error, load_errors, profits }

}

export default getOrders

我能够在模板标签之间正确打印利润数组,但我不能在 setup() 函数中。我刚刚收到一个对象,我无法访问嵌套在其中的数组。基本上我需要在 new_series 中设置利润数组来绘制顶点图表中的累积利润。

这是我从组件打印 DOM 的profits.value:

在此处输入图像描述

标签: javascriptvue.jsdomvue-componentvue-router

解决方案


在您的 console.log('ARRAY', profit) 中,您不能访问 profit.value,而您在其他任何地方都这样做。当您从设置函数返回利润时,该模板了解如何自动访问该值。

const profitsValue = profits.value;
console.log('ARRAY', profitsValue);

然后,您可以在您的系列中使用该值并保留您当前的来自 setup() 的返回语句


推荐阅读