通过Axios收到的Vue2搜索列表

时间:2017-12-11 17:54:56

标签: vue.js vuejs2 vue-component

因为过滤比Vue 1复杂得多,所以我有一个问题。

这是我的组件,其中显示了绵羊列表,其中包含搜索/过滤名称或族的选项。 但我无法弄清楚如何实现这一目标。

<input type="search" v-model="search" placeholder="Search for Name OR Family" />
<ul>
    <li v-for="sheep in sheeps"> <!-- Tried also: 'sheep in filteredSheeps' -->
        {{ sheep.name }} ({{ sheep.type }}/{{ sheep.family }} )
    </li>
</ul>
<script>
import axios from 'axios';
export default {
    data() {
            return {
                sheeps: [],
                search: '',
            };
        },
        mounted() {
            this.getSheeps();
        }
        methods: {
            getSheeps() {
                var self = this;
                const url = '/api/sheeps';
                axios.get(url).then(function(response) {
                    self.sheeps = response.data;
                });
            },
        },
        computed: {
            filteredSheeps: function() {
                var self = this;
                return this.sheeps.filter(function(item) {
                    return item.family.toLowerCase().indexOf(self.search.toLowerCase()) > -1
                })
            }
        }
    }
}
</script>

我认为它需要filteredSheeps中的计算方法v-for,但事实并非如此。直接获得错误: TypeError: null is not an object (evaluating 'item.family.toLowerCase')"

1 个答案:

答案 0 :(得分:2)

这是一个计算方法,可以保护您免受未填充family和/或name的情况的影响。

filteredSheeps: function() {
  let searchTerm = (this.search || "").toLowerCase()
  return this.sheeps.filter(function(item) {
    let family = (item.family || "").toLowerCase() 
    let name = (item.name || "").toLowerCase()
    return family.indexOf(searchTerm) > -1 || name.indexOf(searchTerm) > -1
  })
}

一个有效的例子。

&#13;
&#13;
console.clear()

const sheeps = [
  {name: "Lily", type: "Dorper", family: "Family 1"},
  {name: "Joe", type: "Merino", family: "Family 2"},
  {name: "Bob", type: "Dorper", family: null},
]

new Vue({
  el: "#app",
  data:{
    sheeps:[],
    search: null
  },
  computed: {
    filteredSheeps: function() {
      let searchTerm = (this.search || "").toLowerCase()
      return this.sheeps.filter(function(item) {
        let family = (item.family || "").toLowerCase() 
        let name = (item.name || "").toLowerCase()
        return family.indexOf(searchTerm) > -1 || name.indexOf(searchTerm) > -1
      })
    }
  },
  created(){
    setTimeout(() => this.sheeps = sheeps, 500)
  }
})
&#13;
<script src="https://unpkg.com/vue@2.4.2"></script>
<div id="app">
<input type="search" v-model="search" placeholder="Search for Name OR Family" />
<ul>
    <li v-for="sheep in filteredSheeps"> 
        {{ sheep.name }} ({{ sheep.type }}/{{ sheep.family }} )
    </li>
</ul>
</div>
&#13;
&#13;
&#13;