javascript - 从导入的 .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:
解决方案
在您的 console.log('ARRAY', profit) 中,您不能访问 profit.value,而您在其他任何地方都这样做。当您从设置函数返回利润时,该模板了解如何自动访问该值。
const profitsValue = profits.value;
console.log('ARRAY', profitsValue);
然后,您可以在您的系列中使用该值并保留您当前的来自 setup() 的返回语句
推荐阅读
- c# - 这种技术有名称吗?它是代码味道吗?
- python - multiprocessing.pool.ThreadPool 的内存访问警告,或者可以使用可变参数修复?
- postgresql - Clojure java.jdbc return-keys 选项只返回一行
- python-2.7 - pip install --upgrade fitsio:ValueError:无法配置cfitsio 3470
- triggers - 当父项上的字段更改时触发使用父值更新子项
- android - 使用黄油刀无法正确找到初始化视图
- python - 如何在 Python 中指定线性系统的时间延迟?
- python - Python OpenCV 将平面 YUV 4:2:0 图像转换为 RGB -- YUV 数组格式
- javascript - 如何让我的简单弹出式网页响应式?
- python - 使用正则表达式作为 URL 地址?