Vue.js: The Power of Manipulating Strings

Why is the filter method not working with this.userId, but it is working with the hard-coded value "admin"? How can I resolve this issue?

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

The code that is currently working:

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

I suspect the problem lies in the comparison of strings.

Thank you.

Answer №1

The reason for this issue being undefined is due to the lack of binding to your fn function. Try using arrow syntax in order to establish lexical binding of this to the fn function, which should resolve the problem.

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

Answer №2

You have the option to utilize an arrow function as explained in the answer provided by @Satyam Pathak, or you can define an object outside of this.Messages.filter and use that object in the condition, like this:

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. Check out How does the "this" keyword work? for more detailed explanations.

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

Is there a way to calculate the total of three input values and display it within a span using either JavaScript or jQuery?

I have a unique challenge where I need to only deal with positive values as input. var input = $('[name="1"],[name="2"],[name="3"]'), input1 = $('[name="1"]'), input2 = $('[name="2"]'), input3 = $('[name=" ...

Ways to show alternative data from a database in Laravel 8

I am working on a project where I need to display additional data based on the option selected from a dropdown menu populated from a database. Can anyone guide me on how to achieve this using javascript or jquery? https://i.stack.imgur.com/k3WLl.png Belo ...

Is it possible to transfer a value when navigating to the next component using this.props.history.push("/next Component")?

Is there a way I can pass the Task_id to the ShowRecommendation.js component? recommend = Task_id => { this.props.history.push("/ShowRecommendation"); }; Any suggestions on how to achieve this? ...

How can I effectively refresh the provider_token / access token for Discord in NextJS with Supabase Auth?

Currently, I have encountered an issue with my NextJs project using Supabase Auth for authentication. I am currently utilizing the Discord provider and everything works fine initially. However, after a few minutes, the session object gets updated and the p ...

Identifying activity on a handheld device

I am currently working on a website and I have noticed that it doesn't work as well on mobile devices as it does on desktop. There are performance issues that need to be addressed. I've seen other websites redirecting users to a different page wh ...

Only initiate an AJAX call if there are no other pending AJAX requests from prior function invocations

Arriving at a new, chaotic code base with no testing available has presented me with a significant challenge. I am currently struggling to resolve an issue without the use of ES6, only relying on plain vanilla JS and jQuery. The scenario: Within a web pag ...

Set up webpack on your Mac using npm

Seeking help to install webpack using npm: sudo npm install -g webpack The following error message is encountered: node-pre-gyp WARN Using needle for node-pre-gyp https download node-pre-gyp WARN Pre-built binaries not installable for <a href="/cdn- ...

The Protractor tool (node:9208) threw an UnhandledPromiseRejectionWarning due to an ElementNotVisibleError, indicating that the element is not interactable. Despite this

I am attempting to interact with an element using protractor but encountering the following error (node:9208) UnhandledPromiseRejectionWarning: ElementNotVisibleError: element not interactable (Session information: chrome=69.0.3497.92) (Driver informa ...

My div does not refresh when using .load

I implemented ajax to retrieve the start time and end time from another page, and used setInterval to call this function every second like so. setInterval(function () { CheckTime() }, 1000); function CheckTime() { $.ajax({ url: "Get_TIme. ...

Utilizing V-If and V-Else for Data Value Interpolation - A Guide

In my app, there's a paragraph that users can translate with the click of a button. I use props (props.row.text) and data (this.data.translatedText) to display the text. The data property is initially empty/null, leading to a "data is null" error in ...

Unlocking the mysteries of State and Getters in Nuxt.js: Getters are failing to function

I'm diving into the world of Vue and Nuxt as I embark on creating my inaugural website in Universal mode using these frameworks. The concept of the store in Nuxt has me a bit perplexed. Despite following the official documentation, I am unable to imp ...

Converting MSK time to SST time using JavaScript: A Handy Guide

My API returns time in the format: 07:00 PM This timestamp is based on MSK (Moscow Standard Time) and I need it converted to SST (Singapore Standard Time) using either JavaScript or an npm package. ...

Looking to set up an event listener for a customized checkbox in a Kendo UI Grid column with Vue Js?

Can someone help me figure out why my method checkboxToggle() is not working when I click on the checkbox? Here is the code snippet: ` Methods:{ toggleTemplate(){ let template = `<label class="switch" > <input type= ...

JSP form continues to submit despite JavaScript validation returning false

On my JSP page, I have a form named "deleteCont" and a JavaScript function called "validateDelete". When the user clicks the "Delete contact" button, the "validateDelete" function is triggered successfully, showing an alert message. Unfortunately, even whe ...

Display different text based on the property value

I need to display different text based on the value of a property, showing "offline" if camera.key is null and "online" otherwise. Here's the template I'm using: <h3>Camera sensors</h3> <table> <th>Name</th> ...

Customized style sheets created from JSON data for individual elements

One of the elements in the API requires dynamic rendering, and its style is provided as follows: "elementStyle": { "Width": "100", "Height": "100", "ThemeSize": "M", "TopMargin": "0", " ...

Store the numeric value in JavaScript as a PHP integer

My goal is to obtain the width of the browser and then compare it as a PHP variable. However, the issue I am facing is that it is being saved as a string, and my attempts at parsing it to another variable only result in returning 0. $tam='<script& ...

Please indicate the decimal separator for the Number() function

UPDATE : TITLE IS MISLEADING as testing showed that Number() returned a dot-separated number and the HTML <input type="number"/> displayed it as a comma due to locale settings. I changed to using an <input type="text"/> and filtered keydown lik ...

PHP Calculator - Displaying results in both the webpage and an Ajax popup for enhanced user experience

UPDATE - the issue was resolved by incorporating $('.popup-with-form').magnificPopup('open'); into the StateChanged function in the JavaScript. Many thanks to @Bollis for the assistance. The Initial Query: I have a basic calculator lo ...

The website code lacks a dynamically generated <div> element

When using jQuery to dynamically add content to a "div" element, the content is visible in the DOM but not in the view page source. For example: <div id="pdf"></div> $("#btn").click(function(){ $("#pdf").html("ffff"); }); How can I ensur ...