【问题标题】:Data Object unable to summation inside the computed properties in VUE js 3数据对象无法在 VUE js 3 中的计算属性内求和
【发布时间】:2021-07-05 14:03:45
【问题描述】:

让我们看看 vue.js 3 中的以下代码段,

<template>
  <div>
        <h2>Computed Total - {{getPrice()}}</h2>
  </div>
</template>

<script>
export default {
    name: "ComputedProperties",
    data(){
        return{
            items: [
                {
                    id: 1,
                    title: 'TV',
                    price: 100,
                },
                {
                    id: 2,
                    title: 'Phone',
                    price: 200,
                },
                {
                    id: 3,
                    title: 'Laptop',
                    price: 300
                }
            ]
        }
    },
    computed: {
        getPrice(){
            return items.reduce((total, curr) => (total = total + curr.price), 0)
        }
    }
}
</script>

运行此代码后显示,error 'items' is not defined no-undef 正如我们所知,计算属性不需要声明任何参数。那么代码有什么问题呢?

【问题讨论】:

    标签: vue.js vuejs3 computed-properties


    【解决方案1】:

    您的代码存在一些问题:

    1. 使用计算属性时,不要使用() - 它是属性,而不是函数

    &lt;h2&gt;Computed Total - {{ getPrice }}&lt;/h2&gt;

    1. datacomputedmethods 的所有成员在 Vue 组件的 script 部分使用时,必须用 this 引用 ...例如 this.items
    computed: {
            getPrice() {
                return this.items.reduce((total, curr) => total + curr.price, 0)
            }
        }
    

    【讨论】:

    • 我已将其更改为

      Computed Total - {{ getPrice }}

      但这里仍然存在同样的问题...:(
    猜你喜欢
    • 1970-01-01
    • 2019-12-05
    • 2019-09-22
    • 2019-08-12
    • 2021-05-04
    • 2020-10-02
    • 2017-06-30
    • 2018-02-12
    • 2016-04-18
    相关资源
    最近更新 更多