Vue.js空过滤器结果

在Vue中,我必须过滤一些数据:

<input v-model="search">
<ul>
    <li v-repeat="photo in photos | filterBy search in 'name'">
        <img src="{{ photo.src }}" alt="{{ photo.name }}">
    </li>
    <li v-if="!photos.length">
        No results, sorry!
    </li>
</ul>

如何检测空的过滤器结果并向用户显示适当的消息?

编辑

我目前正在执行以下操作,我认为这是一个很棘手的解决方法:

HTML:

<input v-model="search">
<ul>
    <li v-repeat="photo in photos">
        <img src="{{ photo.src }}" alt="{{ photo.name }}">
    </li>
    <li v-if="!photos.length">
        No results, sorry!
    </li>
</ul>

Javascript:

var v = new Vue({
    data: {
        allPhotos: [...],
        photos: [],
        search: '',
    },
    ready: function () {
        var filter = Vue.filter('filterBy');
        var self = this;
        this.$watch('search', function () {
            self.photos = filter(self.allPhotos, self.search, 'name');
        }, {
            immediate: true
        });
    }
})
飞云猪猪前端2020/03/19 10:12:36

HTML / CSS解决方案(以防万一,如果您仍然尝试在两年后对其进行修复)

/* all list items are visible */
ul.that-list li { display: block; }

/* ...exept last one*/
ul.that-list li:last-child { display: none; }

/* but if last one is also first one ... means the only one */
ul.that-list li:first-child { display: block; }
<h2>List with items</h2>
<ul class="that-list">
  <!-- here is your v-for with any filters you want -->
  <li>1 - Item is here</li>
  <li>2 - Another One Here</li>
  <li>3 - And anothe one</li>
  <!-- this is your message -->
  <li>(!message) There is no items... sorry</li>
</ul>

<h2>Empty</h2>
<ul class="that-list">
  <!-- v-for with no rendered items :c -->
  <li>(!message) There is no items... sorry</li>
</ul>

也codepen链接在这里

小小村村宝儿2020/03/19 10:12:36

在HTML中:

<input v-model="search">
<h4 v-if="!filteredPhotos.length">No results</h4>
<ul>
    <li v-for="photo in filteredPhotos">
        <img :src="photo.src" :alt="photo.name">
    </li>
</ul>

在JS中,您需要使用以下计算属性:

computed: {
  filteredPhotos: function () {
      return this.photos.filter(function(photo){
          return photo.name.indexOf(this.search) > -1;
      }.bind(this));
  }
}

演示:http//jsfiddle.net/crswll/Lr9r2kfv/37/