我尝试将本地过滤器与 v-for
结合使用,但收到错误
Property or method "filterByTitle" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.
下面的代码
<template>
<div class="row">
<div class="col pt-5">
<ul class="blog-list-single" v-for="(post, index) in posts | filterByTitle" :key="index">
<li class="title">{{ post.title }}</li>
<li class="author">{{ post.author }}</li>
</ul>
</div>
</div>
</template>
<style lang="scss">
</style>
<script>
export default {
data() {
return {
posts: [
{ title: 'a', author: 'nd' },
{ title: 'b', author: 'nd' },
{ title: 'c', author: 'nd' },
],
selectedValue: 'a',
}
},
filters: {
filterByTitle(value) {
return value.filter(el => el.title == this.selectedValue)
}
},
}
</script>
最佳答案
过滤器为limited in Vue 2主要用于格式化字符串插值。您现在还可以在 v-bind 表达式中使用它们。
在 Vue 2 中,您可以使用计算属性来过滤这样的列表。
console.clear()
new Vue({
el: ".row",
data() {
return {
posts: [{
title: 'a',
author: 'nd'
},
{
title: 'b',
author: 'nd'
},
{
title: 'c',
author: 'nd'
},
],
selectedValue: 'a',
}
},
computed: {
filterByTitle() {
// return the whole list if there is no filter value
if (!this.selectedValue) return this.posts
// otherwise return the list filtered by title
return this.posts.filter(el => el.title == this.selectedValue)
}
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
<div class="row">
<div class="col pt-5">
<ul class="blog-list-single" v-for="(post, index) in filterByTitle" :key="index">
<li class="title">{{ post.title }}</li>
<li class="author">{{ post.author }}</li>
</ul>
</div>
</div>
关于javascript - vue v-for 带过滤器给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47043897/