我在设置计算属性(数组)时遇到问题。我的Vue组件中具有以下computed
属性:
posts: {
get () {
if ( this.type == 'businesses' || this.type == 'business' ) {
return this.$store.getters.getAllBusinesses.map(_business => {
return _business
})
} else if ( this.type == 'shops' || this.type == 'shop' ) {
return this.$store.getters.getAllShops.map(_shop => {
return _shop
})
} else if ( this.type == 'events' || this.type == 'event' ) {
return this.$store.getters.getAllEvents.map(_event => {
return _event
})
} else {
return this.$store.getters.getAllBusinesses.map(_business => {
return _business
})
}
},
set (posts) {
console.log(posts)
this.posts = posts // Doesn't work - this causes a maximum call stack error, recursively setting itself obviously.
return posts // Doesn't work either - this.posts doesn't seem to be changing...
}
},
console.log(posts)正是我想要的-经过过滤的帖子数组,请参见下面的控制台日志输出。
我的问题很简单:我该如何更新计算的帖子值?
如果有用,我将对帖子进行以下操作:
let filteredPosts = []
this.posts.filter(_post => {
_post.category.forEach(category => {
if ( this.categoryFilters.includes(category.slug) ) {
filteredPosts.push(_post)
}
})
})
let uniqueFilteredPosts = [...new Set(filteredPosts)];
this.posts = uniqueFilteredPosts
这纯粹是为了过滤它们。我的console.logging完全符合我的要求。因此,这可能是一个红色鲱鱼。
任何亲Vue提示将不胜感激!
答案 0 :(得分:0)
如果要使用computed setter,通常会将其分配给计算的get
函数基础上的任何值。请参见链接中的示例。
以您的情况为例,您检查this.type
并根据此信息从商店退回。设置者可能应该检查this.type
并根据它们在商店中进行 set 设置。