【问题标题】:How to get computed property data in method in Vue js?如何在Vue js的方法中获取计算的属性数据?
【发布时间】:2020-10-02 00:40:44
【问题描述】:

我有一个计算属性

 computed: {
    totalwishlistItems () {
      const totalwishlistItems = this.items
      const totalreversedItems = totalwishlistItems.map((item, index) => totalwishlistItems[totalwishlistItems.length - 1 - index])
      return totalreversedItems.length
    }
}

我想要这个 totalwishlistItems 方法中的数据

methods : {
getPosts () {
      for (let i = 0; i < this.totalwishlistItems; i++) {
        this.posts.push({first: 'John',
          last: 'Doe',
          suffix: '#' + i})
      }
    }
}

如何在 Vue js 的方法中获取计算数据的值?

【问题讨论】:

  • this.totalwishlistItems
  • 这就是您访问计算属性的方式,而不是像这样this.totalwishlistItems()。您是否遇到错误,或者您是否进行过任何调试
  • 计算属性顾名思义是属性而不是函数。正如@Tomm 所说,您需要使用this.totalwishlistItems。如果它不起作用,请告诉我们您遇到了什么错误或您如何知道它“不起作用”
  • totalwishlistItems 是如何填充的?你是在填写 totalwishlistItems 之前调用 getPosts 吗?可能存在一些我们在您当前的问题中看不到的异步问题。
  • 你的totalwishlistItems 计算属性应该返回totalreversedItems totalreversedItems.length,确定吗?

标签: vue.js vuejs2 vue-component vuex


【解决方案1】:

忽略反过来,这是处理存储数据和计算属性的方法。

computed: {
    items () {
        return this.$store.state.wishlist.items
    },
    itemCount () {
        // assuming this.$store.state.wishlist.items is array
        return this.items.length
    }
},
methods: {
    getPosts () {
        for (i = 1; i <= this.itemCount; i++) {
            this.posts.push({
                first: 'John',
                last: 'Doe',
                suffix: '#' + i
            })
        }
    }
}

【讨论】:

  • 这显示了如何使用存储数据和本地计算属性。填充商店数据可能还有其他问题,我看不出商品数量和发布请求之间的关系。
  • 我已经在前端检查了它的工作正常,不知道你为什么担心一些问题?
  • $store.dispatch 有什么用? @zed
  • 感谢 zed 快速回复
【解决方案2】:

在调用计算函数时,您必须将它们视为变量。计算函数可以有一个 getter 和一个 setter。

如果你有一个 setter,你可以使用类似的东西来触发它:

this.computedVar = 2;

如果你有一个 getter,你可以使用:

this.computedVar;

如您所见,在这两种情况下,您在调用它时都将其视为变量。

【讨论】:

  • 我可以在方法中使用它吗?使用 getter (this.computedVar)。
猜你喜欢
  • 2019-08-12
  • 1970-01-01
  • 2018-01-14
  • 1970-01-01
  • 2017-06-30
  • 2019-01-27
  • 2018-02-12
  • 2021-07-05
  • 2018-02-18
相关资源
最近更新 更多