javascript - 让计算值等待 Vue.js 中的异步数据的可满足方法是什么?

标签 javascript vue.js

假设我从我的 Vue.js 组件中的状态管理器获得了一个产品列表,并且一个计算属性需要该列表来处理它。最后,我的 DOM 取决于后续列表。

<template>
  <span>{{ computedproducts }}</span>
</template>

<script>
export default {

  created () {
    this.$store.dispatch('getProducts')
  },

  computed: {
    products () {
      // Following is asynchronous
      return this.$store.state.products
    },

    computedProducts () {
      // Processing products in some way
      return this.products
    }

  }
}
</script>

我得到一个错误,因为 computedProducts 在开始时不存在。

一个可能的解决方案是设置:

<span v-if="products.length > 0">{{ computedproducts }}</span>

并且还从产品状态返回一个 Promise 并在 created Hook 处处理产品。但是感觉被黑了。有没有更好的方法?

最佳答案

我会做这样的事情:

export default {
  data() {
    return { products: [] }
  },

  created () {
    this.$store.dispatch('getProducts').then(res => { this.products = res })
  },

  computed: {
    computedProducts () {
      // Processing products in some way
      return this.products
    }
  }
}

Live Demo.

关于javascript - 让计算值等待 Vue.js 中的异步数据的可满足方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42352560/

相关文章:

vue.js - Vue-CLI 3.0 - 如何更改生产链接?

javascript - vuejs 组件模板文件

javascript - 请求的资源上不存在 'Access-Control-Allow-Origin' header 。 Origin 'https ://myappurl. com 因此不允许访问

javascript - Griddle 子网格在渲染时折叠

javascript - 禁用单击时创建数据表按钮

javascript - 如何移相器 : to change image file

javascript - jQuery Mobile - 如何从服务器调整我的图像大小以适应 ListView 图像框

javascript - 为什么 fetch 返回 promise 未决?

vue.js - 从短代码动态注入(inject) Vue 2 组件

javascript - 将 Prop 传递到模板中