[英]Save API data into an array with vue.js
我需要帮助来做这件事。 我想将 API 中的用户列表保存到一个数组(称为“名称”)。 我怎样才能做到这一点? 我试过这个 forEach 但不能让它工作。 谢谢!
编辑:我包装了 function,仍然无法正常工作。
import axios from 'axios'
export default {
data () {
return {
info: null,
name: []
}
},
mounted () {
axios
.get('http://localhost:3000/api/users/', {mode: 'no-cors'})
.then(response => (this.info = response.data))
.then(() => info.data.forEach(element => {
}))
.catch(error => {
console.log(error)
this.errored = true
})
.finally(this.loading = false)
}
}
从上面的代码中,我假设this.info
中的数据是正确的。 我在您的代码中看到的问题是:
1.
.then(response => (this.info = response.data))
.then(() => info.data.forEach(element => {
}))
info
看起来是未定义的。 我认为这应该是this.info
。
.then(response => (this.info = response.data))
.then(() => this.info.data.forEach(element => {
}))
或者,如果您使用箭头 function 语法并返回赋值表达式,您可以使用
.then(response => (this.info = response.data))
.then(info => info.data.forEach(element => {
}))
我真的不推荐,因为一些 linting 规则不允许返回赋值表达式(有充分的理由)。 链接依赖于这种隐式语言行为的 promise 会使代码不易理解。
2.
forEach
的作用很重要。 Vue 的反应性不会采用某些赋值语法,即this.name[i] = element
。 您可以使用push
等数组方法,但我建议您使用函数式编程运算符,例如map
和filter
:
.then(() => (this.name = this.info.data.map(element => {
})))
也许this
引用不正确,因为回调方法在另一个上下文中,请尝试:
export default {
data () {
return {
info: null,
name: []
}
},
mounted () {
var self = this
axios
.get('http://localhost:3000/api/users/', {mode: 'no-cors'})
.then(response => (self.info = response.data))
.then(info.data.forEach(element => {
});)
.catch(error => {
console.log(error)
this.errored = true
})
.finally(this.loading = false)
}
}
您忘记将回调封装到接收info
变量的 function 中,试试这个:
import axios from 'axios'
export default {
data () {
return {
info: null,
name: []
}
},
mounted () {
axios
.get('http://localhost:3000/api/users/', {mode: 'no-cors'})
.then((response) => response.data.forEach(element => {
}))
.catch(error => {
console.log(error)
this.errored = true
})
.finally(this.loading = false)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.