Vue.js重用过滤器

时间:2016-03-03 16:18:19

标签: javascript filter vue.js

我已经制作了这两个过滤器:

过滤1

  Vue.filter('role',function(value,role)
        {
            if(!role || 0 === role.length)
            {
                return value;
            }
            return value.filter(function(item) {
                return item.role.RoleName == role
            });
        });

过滤2

    Vue.filter('company',function(value,company)
        {
            if(!company || 0 === company.length)
            {
                return value;
            }
            return value.filter(function(item) {
                return item.department.company.CompanyName == role
            });
        });

现在我想把它们结合起来。像这样:

合并过滤器

  Vue.filter('employeefilter',function(value,employeeinfo,filteron)
        {
            if(!employeeinfo || 0 === employeeinfo.length)
            {
                return value;
            }
            return value.filter(function(item) {
                return item.filteron == employeeinfo
            });
        });

我把它传递给组合过滤器:

v-for="employee in list | employeefilter selectedrole 'role.RoleName'

但这不起作用我怎么能修复^

修改

我现在就这样传递:

v-for="employee in list | employeefilter selectedrole 'item.role.RoleName'| employeefilter selectedcompany item.department.company.CompanyId"

错误:

Uncaught TypeError: Cannot read property 'replace' of undefined

1 个答案:

答案 0 :(得分:1)

相关:Using variable keys to access values in JavaScript objects

从那个答案:

您可以通过点表示法或括号表示法访问对象属性。

var x = {'test': 'hi'};
alert(x.test); // alerts hi
alert(x['test']); // alerts hi

如果您有动态值,则必须使用后者:

var property = 'test';
alert(x.property); // looks for x.property, undefined if it doesn't exist
alert(x[property]); // looks for x['test'], alerts hi

所以你需要这样做:

return value.filter(function(item) {
    return item[filteron] == employeeinfo
});

编辑,实际上它不会起作用,因为您还需要解析filteron字符串(item['role.RoleName']无法正常工作,item['role']['RoleName']就是您想要的。请查看此答案一个函数,允许您使用字符串Accessing nested JavaScript objects with string key

访问对象的深层属性

最终代码:

Object.byString = function(o, s) {
    s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
    s = s.replace(/^\./, '');           // strip a leading dot
    var a = s.split('.');
    for (var i = 0, n = a.length; i < n; ++i) {
        var k = a[i];
        if (k in o) {
            o = o[k];
        } else {
            return;
        }
    }
    return o;
}

Vue.filter('employeefilter',function(value,employeeinfo,filteron)
    {
        if(!employeeinfo || 0 === employeeinfo.length)
        {
            return value;
        }
        return value.filter(function(item) {
            return Object.byString(value, filteron) == employeeinfo;
        });
    });