1

why filter is not working with this.userId but working with hard code value "admin"? How can I fix this?

computed: {
    UidMessages: function() {
       return this.Messages.filter(function(m) {
         return m.to == this.userId;
     })
   }
 },

And it does work =>

computed: {    
   AMesseg: function() {
     return this.Messages.filter(function(m) {
       return m.to== "admin"
     })
   }
},

I think it's because of the comparison of the strings

Thanks.

Karan
  • 12,059
  • 3
  • 24
  • 40
rafiki
  • 13
  • 4

2 Answers2

1

this getting undefined here because it's not binding to your fn. Use arrow syntax to lexically bind this to the fn and it should work

 computed: {
    UidMessages: function() {
       return this.Messages.filter(m => {
         return m.to == this.userId
     })
   }
  },
Satyam Pathak
  • 6,612
  • 3
  • 25
  • 52
0

You can use arrow function as mentioned in answer by @Satyam Pathak or you can declare object outside of this.Messages.filter and use that object in condition. like below.

computed: {
  UidMessages: function() {
     let userId = this.userId;    // declare and assign userId value.
     return this.Messages.filter(function(m) {
       return m.to == userId;     // use userId variable for condition.
   });
 }
}

P.S. Refer How does the "this" keyword work? for more details.

Karan
  • 12,059
  • 3
  • 24
  • 40