javascriptvue.jshardcode

How to get current name of route(such as 'this' value)in Vuejs?


I am a newbie of vueJS and I would like to use the following template to start my project and I would like to convert it work with IE11

Link : codepen erickarbe/pen/pLbRqQ

The original code is:

computed: {

filteredMembers() {
  return this.members.filter(member => {
    
    let first = member.First.toLowerCase()
    let last = member.Last.toLowerCase()
    
    let fresult = first.includes(this.searchQuery.toLowerCase()) 
    let lresult = last.includes(this.searchQuery.toLowerCase()) 
     
    if(fresult)
      return fresult
    
    if(lresult)
      return lresult
  })
}, 

In order to work with IE11 and I try to use polyfill and convert the code to

computed: {
filteredMembers: function(){  
  return this.members.filter(function(member){
    
    let first = member.First.toLowerCase()
    let last = member.Last.toLowerCase()

   //Error for 'this' 
    let fresult = first.includes(this.searchQuery.toLowerCase())  //'this' Error 
    let lresult = last.includes(this.searchQuery.toLowerCase())  //'this' Error 
   //Error for 'this'

    if(fresult)
      return fresult
    
    if(lresult)
      return lresult
  })
},}

I have Error When I using 'this' on this.searchQuery.toLowerCase())

but I can solve it using 'var ths = this' like

 computed: {
    filteredMembers: function(){
      var ths = this;  
        ........
      let fresult = first.includes(ths.searchQuery.toLowerCase())
      let lresult = last.includes(ths.searchQuery.toLowerCase())

Is it very hardecode or stupid way to get 'this' value???

Is there any best way to get current 'this' value,Thank you very much


Solution

  • Please read about how the this keyword works in JavaScript.

    You just need to bind the original this to the new function:

    return this.members.filter((function (member) {
      // ...
    }).bind(this))
    

    The extra () around the function may not be necessary, but I wasn't sure if IE11 would work without it.