If I do not utilize v-model within computed, then computed will not provide a value

I'm fairly new to coding in JS and Vue.js. I've been attempting to create a dynamic search input feature that filters an array of objects fetched from my API based on user input. The strange issue I'm coming across is that the computed method returns no data unless I use this.term before the return statement. It could be something as simple as a console.log() or any other action involving my v-model. What am I overlooking here?

var stops = new Array();
  document.addEventListener("DOMContentLoaded", () => {
    fetch('http://localhost:8080/api/stops/')
      .then(response => response.json())
      .then((data) => {
        window.data = data;

        Object.keys(window.data).forEach(k => {
          stops.push(window.data[k]);
        });
      })
      .catch(err => {
        console.log(err);
      });

  });


  Vue.component('sidebar', {
delimiters: ['{(', ')}'],
data: () => {
  return {
    term: '',
  }
},
computed: {
  filtered() {

    <!--followng line needs to be here for the func to return data-- >
    this.term = this.term 

    return stops.filter(p => p.nameno.toLowerCase().includes(this.term.toLowerCase()));
  }

},
template:

  `
    <div id="sidebarContain" >
        <input id="sidebar-search" type="text" v-model="term" >

        <div v-for="tram in filtered" :key="tram.name">
            <span >{(tram.nameno)}</span>
            <span ></span>
        </div>
    </div>
`,
methods: {
},
});

Answer №1

The reason for this issue is because the variable stops is not included in your Vue data object, which means it cannot react to any changes. To resolve this problem, you need to move the loading logic into the mounted method, create a stops property in the data object, and set it using this.stops = ... within the mounted method:


Vue.component('sidebar', {
  delimiters: ['{(', ')}'],
  data: () => {
    return {
      term: '',
      stops: []
    }
  },
  computed: {
    filtered() {
      this.term = this.term 

      return this.stops.filter(p => p.nameno.toLowerCase().includes(this.term.toLowerCase()));
    }
  },
  mounted() {
    fetch('http://localhost:8080/api/stops/')
      .then(response => response.json())
      .then((data) => {
        window.data = data;

        Object.keys(data).forEach(k => {
          this.stops.push(data[k]);
        });
      })
      .catch(err => {
        console.log(err);
      });
  },
  template:
    `
      <div id="sidebarContain" >
          <input id="sidebar-search" type="text" v-model="term" >

          <div v-for="tram in filtered" :key="tram.name">
              <span >{(tram.nameno)}</span>
              <span ></span>
          </div>
      </div>
  `,
  methods: {
  },
});

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

Steps to Display a JavaScript Function Two Times on a Single Page

Hey there! I'm currently working on a project where I need to display the output of my function in two separate divs. However, when I try to simply output the same ID, it messes up the whole code and the output becomes null. Here's the code snipp ...

The div element is finally loading properly after multiple clicks

I need some assistance with loading dynamic divs in Angular. I have created a button that adds new divs each time it is clicked in a specific area. However, once these new divs are added, they appear incorrectly: https://i.sstatic.net/sAE6q.png After add ...

"Error" - The web service call cannot be processed as the parameter value for 'name' is missing

When using Ajax to call a server-side method, I encountered an error message: {"Message":"Invalid web service call, missing value for parameter: \u0027name\u0027.","StackTrace":" at System.Web.Script.Services.WebServiceMethodData.CallMethod(O ...

The Challenge of Azure App Service Connection Timeouts

We are currently facing an issue with our Azure App Service, which is built in C# .NET 4.7. The application works perfectly fine when running locally, but encounters an error upon publishing to Azure. The error message returned to the client (web UI develo ...

Root location for offline and pre-production in the Backbone boilerplate router

I am currently utilizing the backbone boilerplate found at https://github.com/tbranyen/backbone-boilerplate My development process involves working on static HTML/JS files offline and conducting tests offline before deploying them to another site for pre- ...

The issue of a malfunctioning react TypeScript map when used in conjunction with useContext

I am attempting to retrieve data from the TVMaze API using React, TypeScript, and useContext. Although I can display the data, the useContext does not update with the return value, so when I use the map function, nothing is displayed. Any advice on how to ...

How can I extract the value from the object returned by an AJAX call?

HTML file <div class="container"> <table id="headerTable" class="table table-bordered"> <thead> <tr> <th colspan="2">Header</th> </tr> </thead> <tbody> <c:forEach item ...

Route functions cannot be hoisted in the Express framework

Can someone shed light on why my Express routes aren't hoisted? I keep encountering this error: throw new TypeError('Router.use() requires middleware functions'); The error is not present in the following file: var express = requir ...

Is there a way to cancel hiding on a q-dialog?

I'm currently working on integrating a confirmation modal within a dialog box that includes form input fields. The purpose is to alert the user when they try to exit without saving their changes. The modal should appear every time the user modifies th ...

Advanced automatic type inference for object literals in TypeScript

When working with TypeScript, I often declare generic functions using the syntax: const fn: <T>(arg: T)=>Partial<T> While TypeScript can sometimes infer the type parameter of a function based on its parameters, I find myself wondering if t ...

Having trouble deleting multiple rows with ng-repeat in datatables

Having followed the instructions in this post, I quickly integrated it with jquery datatables. However, the functionality is not as expected. When attempting to delete rows, they do not get deleted. Furthermore, if I navigate to the next page and return, ...

Exclude the UL hierarchy from removing a class in jQuery

Check out this fiddle to see the code snippet: http://jsfiddle.net/3mpire/yTzGA/1/ I am using jQuery and I need to figure out how to remove the "active" class from all LIs except for the one that is deepest within the hierarchy. <div class="navpole"&g ...

Utilizing Dropzone in Vuejs to securely upload to Google Cloud Storage via Signed URL

One way I have found to upload directly to Google cloud storage is by using a form submission. After obtaining a signed URL using Nodejs, the following code can be used: <form action="https://<%=fields.bucket%>.storage.googleapis.com" method="pos ...

Navigating the Basics: Understanding the Four Quadrant Selection Grid in a Material UI & React Pop-Up Form

Sorry if these questions seem silly. I'm diving into React & Material-UI without a mentor to guide me, relying on documentation and tutorials. Is there a better place for quick beginner questions? Maybe a chat forum or Slack group? Not sure if Stack i ...

Reloading the React/Laravel application causes the app to crash and display a blank page

My current setup involves a react application running on the Laravel 5.4 framework. The problem I'm facing is that whenever I refresh a page with a URL structure like {url}/{slug}, it causes issues within the application. Within my App.js file, here ...

Trigger a function upon clicking a DOM element in Vue.js

My goal is to trigger a function whenever I click on elements in the DOM that have a specific class. Despite my efforts, the functionality doesn't seem to work, and no errors are being reported. Here's the relevant code: methods: { ...

Learn the process of implementing multiple onClick listeners in React without deleting the existing ones

I'm facing a tricky situation with adding multiple event listeners based on different conditions. When the first condition is met, I attach a function to the click event: ref.current.onclick = ()=> {function1()} However, when the second condition ...

Although npm successfully loads Grunt, the grunt command is unfortunately not recognized

Previously, I successfully used grunt on this computer for other projects about 4 months ago. Recently, I tried to use grunt for a new project. Despite loading grunt globally and locally, when I type in $ grunt -v, it says grunt is not recognized. It seems ...

Adjust Text to Perfectly Fit Button

I am developing a quiz using bootstrap and javascript. One issue I encountered is that the text in the buttons can sometimes be longer than the button itself. This results in the text not fitting properly within the button, making it unreadable on mobile ...

Can someone help me extract a specific portion and display the dimensions of the area?

In order for the mouse to create a selection range, simply release the mouse after making your selection. The selected area will display the values of width and height on both the X-axis and Y-axis in the designated fields. I am facing this issue and woul ...