Issue with Vue method not providing expected output

As I dive into the world of Vue, I find myself facing a peculiar issue with a method that should return a string to be displayed within a <span>. While I can successfully retrieve the correct value through console.log, it seems to evade passing into the span tag.

window.onload = function () {
    var app2 = new Vue({
      delimiters: ['${', '}'],
      el: '#app2',
      data: {
        jobs: jobsData,
        sectionTitles:  [
          "Administration, Finance, Stategy and Operations",
          "Data",
          "Poverty Research Unit",
          "Product",
          "Programs and Evaluation",
          "Technology",
          "The Service Design Studio"
        ]
      },
      methods: {
        testOne: function(job, taxanomy, mainTag) {
          try {
            job.tags.forEach(tag => {
                if(tag != taxanomy && tag != mainTag)
                {
                  console.log(tag)
                  return tag;
                }
            })
          } catch(err) {
            console.log(`${err} for ${taxanomy} - ${mainTag}`);
          }
        }
      }
    });
}

In the code snippet above, my aim is clearly to obtain a 'tag' value. The statement return tag is intended to provide a string which I then intend to feed into the subsequent script tag.

              <a :href="`${job.url}`">
                  ${job.title}
                </a>
                <span class="text-right">
                  ${ testOne(job, job.taxanomy, job.mainTag) }
                </span>

Despite being able to view the returned string in console.log, the line

${ testOne(job, job.taxanomy, job.mainTag) }
fails to display anything. I opted for ${ } due to a change in delimiters from {{ }} to ${ }. https://i.sstatic.net/5ti4K.png

Answer №1

Always make sure to return a value from testOne. Remember, the value should come from the callback passed to forEach, not just any random place.

If you need to filter jobs based on a condition, consider using filter before returning a value from the array.

 testOne: function(job, taxanomy, mainTag) {
      try {
        const filtered = job.tags.filter(tag => tag != taxanomy && tag != mainTag )
        return filtered[0]
      } catch(err) {
        console.log(`${err} for ${taxanomy} - ${mainTag}`);
      }
    }

Just keep in mind that there might not always be a result in your search.

Also, be prepared to handle cases where your condition returns more than one result.

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

Using node.js to send a response with response.writeHead on the http module

While working on my own custom http module, I stumbled upon a few confusing points while studying the official node.js http module api: When a user utilizes the response.writeHead(statusCode, [reasonPhrase], [headers]) function, are the headers suppose ...

Does shouldComponentUpdate returning `true` have the same effect as not having shouldComponentUpdate at all?

Within my React Native component, I have included a blank shouldComponentUpdate shouldComponentUpdate(nextProps, nextState) { } I am aware, from reading this answer, that an empty shouldComponentUpdate function helps in eliminating unnecessary re ...

Javascript editing enhancement for real-time changes

Are there any tools for in-place editing of Javascript code? I'm looking for something similar to Firebug, which is great for instant CSS editing and previewing but doesn't have the capability to edit JavaScript directly. Is there a tool or addon ...

Instructions for passing a JavaScript variable to a PHP MySQL database

I am attempting to integrate a JavaScript variable into PHP MySQL, but I'm encountering issues with the insertion. Currently, it is being inserted as <javascript>document.write(window.outerWidth); </javascript> x <javascript>document ...

The JavaScript file is not compatible with Internet Explorer 9

My website's JavaScript functions normally work on all browsers except for Internet Explorer 9. In IE7 and IE8, they also work normally. After extensive testing, I have concluded that the JS file simply does not work in IE9, but why is that? The curio ...

Transferring data from a class method to a React component

Situation: In a React component, I have a class with its own methods that is instantiated. What I'm needing: One of the methods in the class changes the value of an input (referred to as `this.$el`) using `.val()`. However, I need to pass this value ...

Error: The function wrapper.find().simulate('keypress', {key: 'Enter', keycode: 13}) is not working as expected

Let's discuss further about this query vue-btn isn't triggering on pressing the enter key I have designed a sign-in page where users can log in by pressing 'Enter' on the keyboard. Now, I aim to perform a unit test that simulates pres ...

In React, is it typical to maintain identical values in both state and ref?

When working with my React app, I encountered a situation where I needed to access state values inside setTimeout() and setInterval(). However, due to closures being bound to their context once created, using state values in these functions would not refle ...

Step-by-step guide on how to show and hide a div by clicking a button with the help of an "

Here is some code that I have written to toggle a div when clicking on a button using vue.js. Instead of using hidden data property, I am trying to achieve this by targeting the div with Id="categories" <button v-on:click="isHidden = !i ...

What is the best way to transfer data between controllers in my particular situation?

Currently, I am working on developing a factory for the restful services. The main challenge I'm facing is how to transfer data from one controller to another in AngularJS. Specifically, I need to use the data obtained from the first service call to ...

What sets Express.js apart from koa2.js in handling asynchronous functions?

I've encountered a situation where I had to set up the router using Express, and it was functioning correctly with the following code: router.get('/',(req,res)=>{ queries.getAll().then(stickers=>{ res.json(stickers) }) ...

Reload entire page for AJAX request if JavaScript is not enabled

Currently utilizing JSF2. I have a button that triggers an action and then updates a section of the page (fairly standard). <h:commandButton value="foo" action="#{myBean.myAction}" > <f:ajax execute="@form" render="#content" /> ...

Encountered a Socket.io issue: CONNECTION_TIMED_OUT_ERROR

I'm in the process of developing a simple HTML chat program. I've set up a node server for testing, but encountering a socket error when trying to access the HTML page. This is my first experience with Node.js and setting up a server, so it' ...

Exploring the depths of nested collections in Angular 12

As I work on my very first Angular/Firestore app, I find myself grappling with understanding how to retrieve data from nested collections. The Firestore database path that I need to access is as follows: /Customer(CollectionName)/cl0Apvalb6c0w9hltQ8AOTF4go ...

Exploring the implementation of Chain Map or Chain Filter within an Angular Http request that delivers a promise

I have a dataset in JSON format that I am working with, and I need to filter out specific key values using lodash. I want to reject multiple keys that I don't need. My initial approach is to either chain the map function and then use the reject funct ...

Exploring the wonders of Angular 2: Leveraging NgbModal for transclusion within

If I have a modal template structured like this: <div class="modal-header"> <h3 [innerHtml]="header"></h3> </div> <div class="modal-body"> <ng-content></ng-content> </div> <div class="modal-footer"& ...

Error encountered when entering a value in the Material UI keyboard date picker

When I select a date by clicking on the calendar, it works fine. However, if I initially set the date to empty and then type in the date, it does not recognize the format and displays numbers like 11111111111111111111. This breaks the date format. If I sel ...

Reorder elements in CSS Grid

I've been working with a css-grid and it's almost there, but I'm stuck on reordering the items in a specific way. Currently, the html layout is set as “1, 2, 3, 4,…10”, but for smaller screens, I want the visual order to be “1, 2, 4 ...

Error in VueJS/Typescript: Module 'my-module' or its type declarations are not found

Hey fellow developers! I'm currently working on a Vue2 setup with Nuxt and Typescript. I'm facing an issue while trying to install the awesome vue-slick-carousel module via yarn. When attempting to import the module in my component, Typescript th ...

struggling to send variables to jade templates with coffeescript and express.js

As a newcomer to node and express, I am currently building the front end of an application that utilizes jade as its templating engine. Despite extensive searching online and within this community, I have not been able to find a solution to a particular is ...