javascript - 如何在 vuejs 中将“.find()”与数组一起使用
问题描述
我的项目组件上有以下代码:
<template>
<div>
<agent
v-for="agent in agents"
:uuid="agent.uuid"
:key="agent.uuid"
:socket="socket">
</agent>
<p v-if="error">{{error}}</p>
</div>
</template>
<style>
body {
font-family: Arial;
background: #f8f8f8;
margin: 0;
}
</style>
<script>
const request = require('request-promise-native')
const io = require('socket.io-client')
const { serverHost } = require('../config')
const socket = io()
module.exports = {
data () {
return {
agents: [],
error: null,
socket
}
},
mounted () {
this.initialize()
},
methods: {
async initialize () {
const options = {
method: 'GET',
url: `${serverHost}/agents`,
json: true
}
let result
try {
result = await request(options)
} catch (e) {
this.error = e.error.error
return
}
this.agents = result
socket.on('agent/connected', payload => {
const { uuid } = payload.agent
const existing = this.agents.find(a => a.uuid === uuid)
if (!existing) {
this.agents.push(payload.agent)
}
})
}
}
}
</script>
似乎一切正常,但是,当我连接代理时,下面一行抱怨......
const existing = this.agents.find(a => a.uuid === uuid)
控制台中的消息 sais 'Uncaught TypeError: n.agents.find is not a function'
我没有看到错误在哪里......有什么帮助吗?太感谢了
更新->这就是我在“结果”中的内容:
{…}
agentMAC: (...)
agentName: (...)
connected: (...)
createdAt: (...)
id: (...)
lastAccess: (...)
loginDate: (...)
pid: (...)
updatedAt: (...)
userId: (...)
__ob__: Ae {value: {…}, dep: fe, vmCount: 0}
get agentMAC: ƒ ()
set agentMAC: ƒ (t)
get agentName: ƒ ()
set agentName: ƒ (t)
get connected: ƒ ()
set connected: ƒ (t)
get createdAt: ƒ ()
set createdAt: ƒ (t)
get id: ƒ ()
set id: ƒ (t)
get lastAccess: ƒ ()
set lastAccess: ƒ (t)
get loginDate: ƒ ()
set loginDate: ƒ (t)
get pid: ƒ ()
set pid: ƒ (t)
get updatedAt: ƒ ()
set updatedAt: ƒ (t)
get userId: ƒ ()
set userId: ƒ (t)
__proto__: Object
解决方案
从您的更新看来,结果值是一个对象,当您将它分配给 this.agents 时,它现在也只是一个对象。如果结果将是单个对象或对象数组,那么最好如下分配结果,以确保它是一个数组。
this.agents = result ? [].concat(result) : []
注意:如果结果未定义/为空,上面的三元检查也将确保分配空数组。
推荐阅读
- kdb - kdb - 排序符号的好方法
- database - EntityFramework.BulkInsert:上下文不包含 BulkSaveChanges 的定义
- c# - 将子章节移动到下一页,如果它们显示在页面末尾(使用 openXML)
- asp.net - 如何在 Azure 存储中查找文件扩展名?
- android - 如何在 kotlin 中正确绑定 recyclerview 项目?
- c# - Xamarin Forms ListView 绑定未更新
- reactjs - 道具验证中缺少 React JS
- angular - 星云登录组件
- sql - 如何在 SQL 中将 JSON 值展平为频率计数
- git - 使用 ssh 进行 git clone 时出现“连接超时”