Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

javascript - 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

question from:https://stackoverflow.com/questions/65660906/how-to-get-current-name-of-routesuch-as-this-valuein-vuejs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...