vue使用computed实现动态过滤
效果:
<div id="test"> Filter:<input type="text" v-model="searchlanguage" /> <ul> <li v-for="language in searchResults"> {{language}} </li> </ul> </div>
new Vue({ el: '#test', data() { return{ searchlanguage: '', devlanguages: [ 'angularjs', 'vue.js', 'asp.net', 'asp.net mvc', 'mysql', 'ms sql server', 'python', '.net core' ] } }, computed: { searchResults() { let filter = new RegExp(this.searchlanguage, 'i') return this.devlanguages.filter(el => el.match(filter)) } } })
computed是计算属性,是基于它们的响应式依赖进行缓存的。即是说,只有在相关响应式依赖发生改变时它们才会重新求值。