在 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
在比较函数中不可访问,但我不确定如何传递这个值?
谢谢!
最佳答案
比较函数中的 this
与 hostelsList 函数中的 this
不相等。
他们有不同的范围。所以你可以或者:
- 使用箭头函数替换您的比较函数,例如
const compare = (a,b) =>{/*...*/}
- 使用 bind 创建另一个具有正确作用域的函数,例如
this.$store.getters.hostels.sort(compare.bind(this))
关于javascript - 在比较函数中设置 sort_by,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55823581/