Skip to content

vue运用lodash自定义过滤器 #18

@Wscats

Description

@Wscats

安装

由于vue2.x版本删除了filterBy等过滤器,我们可以用lodash来模拟过滤器的方法

安装并引用lodash

var Vue = require("vue");
var _ = require("lodash");

使用

页面接受输入框需要搜索的值,和搜索的列表结果

new Vue({
    el: "#demo",
    template: `
		<div>
			<input v-model="search" />
			<select v-model="key">
				<option value="user">user</option>
				<option value="age">age</option>
			</select>
			<ul>
				<li v-for="arr in arrss">name:{{arr.user}}  age:{{arr.age}}</li>
			</ul>
		</div>
	`,
    data: {
        search: "",
        //默认进行名字筛选
        key: "user",
        arrs: [{
            'user': 'wscats',
            'age': 18,
        }, {
            'user': 'oaoafly',
            'age': 16,
        }, {
            'user': 'yao',
            'age': 14,
        }, {
            'user': 'eno',
            'age': 99,
        }]
    }
})

由于过滤器只能用在表达式{{}}中,v-for不能像以前用自定义过滤器配合管道字符|实现过滤筛选,我们选用计算属性来解决这个问题,在计算属性中我们接受输入框的值,并且配合_.filter方法实现弱搜索

computed: {
    arrss() {
        var output;
        if (this.search) {
            //可以传对象或者根据匿名函数的条件进行筛选结果
            output = _.filter(this.arrs, (item) => {
                //遍历每项字符串
                if (_.isString(item[this.key])) {
                    return item[this.key].indexOf(this.search) != -1;
                } else {
                    //数字强制转换为字符串
                    return (item[this.key] + "").indexOf(this.search) != -1;
                }
            })
        } else {
            output = this.arrs
        }
        return output;
    }
}

Lodash

更多关于Lodash请参考Wscats/node-tutorial#16

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions