javascript - 在比较函数中设置 sort_by

标签 javascript vuejs2

在 Vuejs 2.6 应用程序中,我使用比较函数来按 sort_by 进行不同排序:

export default {
    data: function () {
        return {
            ...
            sort_by: null,
        }

    },

    computed: {
        ...
        hostelsList: function() {
            if ( this.sort_by == null || typeof this.sort_by == "undefined" ) {
                this.sort_by= 'price' 
            }
            console.log("this.sort_by::")
            console.log( this.sort_by )


            function compare(a, b) {
                if ( this.sort_by == 'price' ) {
                    if (a.price < b.price)
                        return -1;
                    if (a.price > b.price)
                        return 1;
                } // if ( this.sort_by == 'price' ) {

                if ( this.sort_by == 'rating' ) {
                    if (a.rating < b.rating)
                        return -1;
                    if (a.rating > b.rating)
                        return 1;
                } // if ( this.sort_by == 'rating' ) {

                if ( this.sort_by == 'name' ) {
                    if (a.name < b.name)
                        return -1;
                    if (a.name > b.name)
                        return 1;
                } // if ( this.sort_by == 'name' ) {

                return 0;
            }

            return this.$store.getters.hostels.sort(compare);
        },  // hostelsList: function() {

但是我遇到了这个错误:

app.js?dt=1556086426:98302 [Vue warn]: Error in render: "TypeError: Cannot read property 'sort_by' of undefined"

修改 block : 行:

 console.log("this.sort_by::")
 console.log( this.sort_by )


 console.log("this::")
 console.log( this )

返回 sort_by 的有效值,我不确定其中必须包含什么: enter image description here

我想原因是 sort_by 在比较函数中不可访问,但我不确定如何传递这个值?

谢谢!

最佳答案

比较函数中的 this 与 hostelsList 函数中的 this 不相等。

他们有不同的范围。所以你可以或者:

  1. 使用箭头函数替换您的比较函数,例如
const compare = (a,b) =>{/*...*/}
  1. 使用 bind 创建另一个具有正确作用域的函数,例如
this.$store.getters.hostels.sort(compare.bind(this))

关于javascript - 在比较函数中设置 sort_by,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55823581/

相关文章:

javascript - 禁用移动设备的 Nextgen 灯箱效果?

javascript - 如何让 Angular 等待函数在继续之前返回一个值

javascript - js 带箭头的垂直 slider

vue.js - Vue Mixin 计算函数传递参数

javascript - 通过输入文本过滤 ul 列表 Vue.js 2

javascript - 在 VueJS 中使用计算属性搜索过滤器

javascript 在 document.nameofformtosubmit.submit() 中使用变量值

javascript - 为什么 getElementsByTagName 中返回未定义

typescript - 如何使用编译器包含构建(Vue、Typescript、Webpack)

css - 如何在 vue.js 中做作用域外部 css?