【问题标题】:Passing a value from database to vue component and assigning it to a variable将值从数据库传递到 vue 组件并将其分配给变量
【发布时间】:2020-08-05 23:17:42
【问题描述】:

我正在尝试从我的数据库中传递一个值,然后将该值分配给我的Vue Component 中的一个变量。这成功地从数据库中获取数据,但是在将该值分配给组件中的变量时出现错误:

  • “TypeError:无法读取未定义的属性‘数据’”

Vue 组件:

import TransactionsService from '@/services/TransactionsService'
export default {
    components: {
    },
    data(){
        return {
            transactions: null,
            product: null,
            amount: null
        }
    },
    async mounted() {
        try{
        this.transactions = (await TransactionsService.index()).data.transactions

        for( transaction in transactions){
            this.amount = transaction.amount
        }
        console.log(amount)

        this.userId = this.$store.state.user.priviledge
        } catch(error){
            this.error = error.response.data.message
        }      
    }
}

我想将transaction.amount 的值赋给变量amount

【问题讨论】:

  • TransactionsService.index()的返回数据结构是什么
  • @AndrewNolan 一个数组。我已将其添加到问题中
  • 在通往transactions的路径中似乎不是data
  • 这很奇怪,因为我在我的 html 部分使用transactions,而我使用v-for 来访问和显示这些值。所以我不确定为什么我现在在尝试将其分配给变量时为transactions 收到此错误
  • 我把它改成了console.log(error),现在说transaction没有定义

标签: node.js vue.js vuejs2 vue-component


【解决方案1】:

for ... in 循环中,transaction 是项目的数组索引,而不是项目本身。这是一个更常见的循环:

// forEach
transactions.forEach(transaction => {
   this.amount = transaction.amount 
})

这个循环会起作用,但仍然没有意义,因为您只会将this.amount 设置为下一个transaction 数量并覆盖最后一个。如果您打算将它们相加,您可以使用:

this.amount += transaction.amount 

(注意:最好将任何其他循环类型与数组一起使用,因为for ... in 不能保证索引顺序。替代方案是forEachforfor ... of)子>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-24
    • 2019-11-02
    • 1970-01-01
    • 1970-01-01
    • 2021-02-04
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多