我是Vue的新手。这似乎是一项常见的任务,应该很简单,但是答案让我难以理解。我有一些要过滤的数据,然后在组件中显示计数。
HTML:
<main class="container-fluid">
<div class="row" id="main-app">
<div class="col">
<div class="card border-secondary mb-3" style="min-height: 400px;">
<div class="card-body">
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Find Items" v-model="search">
</div>
</div>
</div>
</div>
<div class="col-md-8">
<div class="card border-secondary mb-3">
<div class="card-body">
<h4 class="card-title">Items <item-counter :count="resultCount"></item-counter></h4>
<div class="row">
<div class="col" id="results">
<ul class="list-group list-group-flush">
<li class="list-group-item" v-for="app in filteredApps" :key="app.id">
<div class="d-flex w-100 h-100 align-self-center">
<a :href="app.link">{{app.name}}</a>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</main>
Vue JS:
var ItemCounter = Vue.component('item-counter', {
props: ['count'],
template: '<span class="badge badge-primary badge-pill">{{ count }}</span>'
});
var vmResults = new Vue({
el: '#main-app',
data: {
search: '',
items: [
{
"id": 1,
"name": "Item 1",
"link": "https://www.google.com"
},
{
"id": 2,
"name": "Item 2",
"link": "https://www.google.com"
},
{
"id": 2,
"name": "Item 3",
"link": "https://www.google.com"
},
]
},
computed: {
resultCount() {
return this.data && this.data.length;
},
filteredApps: function () {
if (this.search.trim() === '') {
return this.items;
} else {
return this.items.filter(function (item) {
let self = this;
return item.name.toLowerCase().indexOf(self.search.toLowerCase()) >= 0;
});
}
}
},
components: {
ItemCounter
}
});
我尝试了几种不同的方法,但是没有用。我在搜索时遇到错误,并且未显示计数。我在做什么错了?
答案 0 :(得分:1)
id
([1、2、2])self/this
技巧没有从函数外部正确保留this
改为使用es6 arrow function:
filteredApps: function() {
if (this.search.trim() === '') {
return this.items;
} else {
return this.items.filter(item => { // <-- es6 arrow function preserves `this`
return item.name.toLowerCase().indexOf(this.search.toLowerCase()) >= 0;
});
}
}
resultCount
应提供过滤结果的长度:resultCount() {
return this.filteredApps.length;
}