How can the current route name be retrieved in Vue.js, similar to obtaining the 'this' value?

As a newcomer to vueJS, I'm eager to use the template below to kickstart my project and make it compatible with IE11:

Link: codepen erickarbe/pen/pLbRqQ

The initial code snippet is as follows:

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
  })
}, 

To make it work in IE11, I attempted to utilize polyfill and modified the code like so:

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 encountered an error when trying to use 'this' for `this.searchQuery.toLowerCase())`.

However, I managed to solve it by using 'var ths = this' as shown below:

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

Is this approach too cumbersome or inefficient for obtaining the 'this' value?

Are there better ways to access the current 'this' value? Thank you!

Answer №1

To understand the inner workings of the this keyword in JavaScript, it is important to delve into its functionality.

A simple solution involves utilizing the bind method to establish a connection between the original this and the new function:

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

While wrapping the function with additional parentheses () may seem unnecessary, it has been implemented as a precautionary measure for compatibility with older browsers like IE11.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a problem with Nginx and WordPress where the admin-ajax.php is causing an issue when returning an AJAX result, leading to an error of Un

Currently, the issue is that everything runs smoothly on my Apache server, but when I switch to Nginx, an error is triggered with Uncaught SyntaxError: Unexpected token < Below is the function extracted from Functions.php function searchranges() { ...

Is there a way to verify the selection of all mandatory fields prior to concealing a div?

var count = 2; $('.next').click(function() { var requiredField = true; $(this).siblings('table').find('tbody tr:nth-child(' + count + ') td').each(function() { var element = $(this).find('center').f ...

Adjusting the bottom property to a negative value in CSS will stretch the page downwards

I want to hide a portion of an HTML element at the bottom of the page and then reveal the entire element by sliding it upwards upon clicking with the help of CSS3 transitions. The expected behavior is for the part of the element extending below the page t ...

How can I make v-on:click trigger a modal for specific objects exclusively?

How can I modify the code below to ensure that when I click on the SAN button, the modal only displays once with the customerName (SAN) inside it? Currently, clicking on SAN, DAVID, or JAY generates the modal three times. This is my template file: <di ...

Clicking on the div will redirect the page to one destination, while clicking on the anchor tag will redirect the page to a different destination

I have a div containing an anchor tag, like so: <div onclick="redirect to one location" style="height:200px;width:200px"><a href="http://www.google.com" >text</a></div> The div has dimensions of 200px by 200px and on click, it sho ...

The function in jQuery that can be used to hide a <div> when clicked

I am facing a problem with my jQuery code that is supposed to remove/hide a specific div. Despite checking various examples, I can't seem to make it work properly. This issue arises in the context of jQuery on Drupal 7. The live site where this proble ...

Leveraging AJAX to send a form filled with dynamic content to multiple destinations

I have a hidden form that needs to be submitted to two different locations. The form is automatically filled using the .val method in jQuery. How can I write the ajax script to submit this form to two different locations? Is it possible to do this without ...

Pass the selected value from jQuery autocomplete to a hidden field

I am attempting to transfer the current value of AutoComplete jQuery to a HiddenField on ASP Hidden Field: <asp:HiddenField ID="hidden" runat="server" /> Upon Page Load, I only set the HiddenField Value to a TextBox: Protected Sub PrepareSession ...

Generate a collection of information by gathering metadata from Xray

I've been struggling to populate an array with metadata retrieved using Xray. The issue arises when the function is called by an API endpoint on my server to fetch links from my application. My main challenge seems to be related to promises, as there ...

What is the best method for retaining the complete YQL outcome within a JavaScript object?

I am trying to store the output of my YQL Query in a JavaScript object Here is my query: SELECT * FROM html WHERE url="http://myurl.com" and xpath="/html/body/center/table[1]/tr" Can someone guide me on how to proceed? I have gone through the YQL docu ...

Showcasing PHP variables within HTML using jQuery

I am currently looking for the best way to showcase information stored in a PHP variable, retrieved from a MySQL database. My initial thought was to use jQuery. Here are my questions: When a user inputs a number into a field, I receive that Member' ...

Failure to update variable with AJAX

Using jQuery When making an AJAX request to update the value of a variable (foo) with a response from the server, I encountered an issue. Here is the code snippet in question: //## Initializing variable ## var foo = ""; //## Sending AJAX requ ...

Measuring the Unquantifiable: Embracing Undefined Values in MongoDB

Issue Despite multiple attempts, the Node.js MongoDB library consistently returns undefined for collection.count({}). I have thoroughly researched previous solutions to similar questions without success - the problem persists and the result is always unde ...

Display a hidden div only when a cookie is set during the initial visit

I'm currently facing an issue while trying to set multiple cookies based on the existence of a div using JavaScript. On the first visit, I want to display the div to the user if it exists, then set a cookie (named redCookie) that expires in 3 days. Up ...

Validating email addresses using jQuery regular expressions

Probable Match: How can I validate email addresses using a regular expression? I have explored various options, but none have proven effective for validating email: [email protected] This is the client-side function I have implemented for a cust ...

Polymer: Issues with cycling through pages using the "Prev" or "Next" buttons

I am currently developing a Polymer app and facing an issue with writing my script in a declarative manner. I keep encountering the error message Uncaught ReferenceError: selectedTestimonial is not defined In addition, the code restricts the array to only ...

Angular 4 Password Regular Expression Not Working

My validation regex checks for at least 8 characters, including one number, one uppercase letter, one lowercase letter, and one special character. Here is the regex I am using: '(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[$@$!%*?&])[A-Za-zd$@$!%*?& ...

Choosing dynamically created components:Making a choice among elements that are generated

Currently, I am working on a task that involves moving list items between two separate lists and then returning them back upon a click event trigger. Below is a snippet of the basic HTML structure: Unchosen: <br> <ul id="unchosen"></ul> ...

Populate a Textbox Automatically using a Dropdown List

MVC 4 Changing multiple display fields based on DropDownListFor selection Having some issues trying to implement the solution mentioned above. It seems like there might be a problem with either my javascript code or the controller. JavaScript in View ...

Unlocking the power of bitwise operations in VueJS with Javascript

Forgive me if this sounds like a silly question. I'm currently using vue-moment within my Vue.js application and I have the following code snippet: <!-- date = '2020-03-23 01:01:01' --> <span>{{ date | moment('from', & ...