我有一个具有 3 个不同优先级的标记工具组件。现在我想过滤搜索。是否可以在计算的 tagsFilter
函数中访问 tags[n]
?
这是我当前的版本:https://jsfiddle.net/hej7L1jy/26/
我想将 v-for="tag in tags[n]"
替换为:v-for="tags in tagsFilter "
在我收到 TypeError: this.tags.filter is not a function
有没有人有想法?
Vue.js 模板:
<div id="app">
<input id="input-search" type="text" class="form-inline pull-right" v-model="textSearch" placeholder='Search...'>
<div v-for="n in prios">
<h3>{{n}} tag priority</h3>
<ul v-if="tagsFilter && tagsFilter.length">
<li :class="'tagPriority-'+n" v-for="tag in tagsFilter">
<label class="checkbox-inline"><input name="tags[]" type="checkbox" v-model="tagSelected" :value="tag.id"> {{tag.title}}</label>
</li>
</ul>
</div>
</div>
Vue.js 组件:
new Vue({
el: '#app',
props: {
selectedTags: {
type: Array
}
},
data() {
return {
prios: [ 1, 2, 3 ],
tagSelected: [],
tags: [],
textSearch: ''
}
},
computed: {
tagsFilter: function() {
var textSearch = this.textSearch;
return this.tags.filter(function(el) {
return el.title.toLowerCase().indexOf(textSearch.toLowerCase()) !== -1;
});
}
},
created: function () {
this.tagSelected = this.selectedTags;
this.tags = {"1":[{"id":9,"title":"Auto"}],"2":[{"id":8,"title":"Elektroauto"}],"3":[{"id":10,"title":"BMW i3"},{"id":11,"title":"Opel Ampera"},{"id":12,"title":"Renault TWIZY"}]};
}
});
最佳答案
尽管您在数据
中定义了标签
:
data() {
return {
tags: [],
}
},
您的创建
回调覆盖 this.tags
:
created: function () {
this.tagSelected = this.selectedTags;
this.tags = {"1":[{"id":9,"title":"Auto"}],"2":[{"id":8,"title":"Elektroauto"}],"3":[{"id":10,"title":"BMW i3"},{"id":11,"title":"Opel Ampera"},{"id":12,"title":"Renault TWIZY"}]};
}
把它变成一个没有filter
方法的对象。
使用计算属性过滤
您的模板:
<li :class="'tagPriority-'+n" v-for="tag in tags[0]">
成为
<li :class="'tagPriority-'+n" v-for="tag in tagsFilter[n]">
和
computed: {
tagsFilter: function() {
var textSearch = this.textSearch;
return this.tags.filter(function(el) {
return el.title.toLowerCase().indexOf(textSearch.toLowerCase()) !== -1;
});
}
},
变成:
computed: {
tagsFilter: function() {
var textSearch = this.textSearch;
var filteredTags = {};
var tags = this.tags;
Object.keys(this.tags).forEach(function(key) {
filteredTags[key] = tags[key].filter(function(el) {
return el.title.toLowerCase().indexOf(textSearch.toLowerCase()) !== -1;
});
});
return filteredTags;
},
},
基本上,我们迭代每个 this.tags
属性并将每个属性的过滤版本添加到 filteredTags
。
使用方法过滤
另一种方法(最少更改的代码)是将您的 computed
更改为带有参数的方法:
<li :class="'tagPriority-'+n" v-for="tag in tags[0]">
成为
<li :class="'tagPriority-'+n" v-for="tag in tagsFilter(n)">
和
computed: {
tagsFilter: function() {
var textSearch = this.textSearch;
return this.tags.filter(function(el) {
return el.title.toLowerCase().indexOf(textSearch.toLowerCase()) !== -1;
});
}
},
变成:
methods: {
tagsFilter: function(i) {
var textSearch = this.textSearch;
return this.tags[i].filter(function(el) {
return el.title.toLowerCase().indexOf(textSearch.toLowerCase()) !== -1;
});
},
},
关于javascript - Vue.js 在计算函数中过滤多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48866505/