【问题标题】:Nuxt JS / Vue JS search filter not workingNuxt JS / Vue JS 搜索过滤器不起作用
【发布时间】:2019-03-03 11:19:32
【问题描述】:

我最近在为物业网站构建搜索组件时得到了一些帮助。我的想法是我有一个带有属性列表的 /properties 页面和一个通用搜索组件,该组件在每个页面上都有一个指向 /properties 的操作和一个 GET 方法。

一个示例搜索可能是:

/properties/?search=Green%20Park&type=Apartment&type=Bungalow&bedrooms=1&county=Blaenau%20Gwent

或者...

/properties/?search=&type=Apartment&bedrooms=1&county=

我有一些代码旨在将过滤后的属性显示为计算属性。但是,else 语句中似乎有问题,它没有返回任何内容。这是我的代码:

computed: {
    filteredProperties: function () {
        let self = this
        let routeConstraints = ['search', 'type', 'bedrooms', 'county'].filter(function (val) {
            return self.$route.query[val] !== undefined
        })
        if (routeConstraints.length === 0) {
            return self.properties
        } else {
            return routeConstraints.reduce(function (acc, val) {
                return acc.filter(function (property) {
                    //basically I am checking if there is some value in the query parameter that matches properties.
                    return self.$route.query[val].some(function (item) {
                        //changed the matching condition to indexOf
                        return property[val].match(item).length > 0
                    })
                })
            }, self.properties)
        }
    }
}

我收到以下错误:

self.$route.query[val].some is not a function

但它只会在尝试使用搜索时出错(参见上面的示例),如果我不使用搜索并直接进入属性页面,它会正常工作:/properties

类型:可以是单一类型,也可以是多个类型。

谁能帮我解释一下为什么它给了我这个错误以及如何解决它?谢谢!

【问题讨论】:

  • self.$route.query[val] 返回一个字符串值,因此您不能使用 some 方法,该方法用于数组。

标签: vue.js nuxt.js


【解决方案1】:

在您给出的示例中,您没有将元素数组传递给查询。当每个查询参数只有一个值时,它会作为字符串返回。当它具有多个值时,例如test=1&test=2,它会返回一个字符串数组。

我认为您真正想做的是测试是否有任何查询参数匹配为键。一种方法是:

return Object.keys(self.$route.query).some(function (item) {
   return property[val].match(item).length > 0
 })

【讨论】:

    【解决方案2】:

    我认为这是错误的,因为你没有使用ES6self 无法识别,你可以使用arrow function 代替,

    computed: {
     filteredProperties() {
        let routeConstraints = ['search', 'type', 'bedrooms', 'county'].filter((val) => {
            return this.$route.query[val] !== undefined
        })
        if (routeConstraints.length === 0) {
            return this.properties
        } else {
            return routeConstraints.reduce((acc, val) => {
                return acc.filter((property) => {
    
                    return this.$route.query[val].some((item)=> {
                        //changed the matching condition to indexOf
                        return property[val].match(item).length > 0
                    })
                })
            }, this.properties)
        }
    }
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-22
      • 1970-01-01
      • 2021-07-29
      • 2018-03-06
      • 2021-11-08
      • 2020-06-08
      • 2017-04-28
      • 2021-05-26
      相关资源
      最近更新 更多