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