What is the best way to display JSON file results when clicking a button using Vue?

Once again, it's me!

Check out my latest project here

I am looking to retrieve data from a json file by inputting the necessary details and clicking on the button.

For instance, let's say we want to find job listings for developers in Istanbul. We fill out the required fields and hit the Find! button.

var app = new Vue({
  el: "#app",
  data: {
    founded: [],
    search: ""
  },
  created() {
    fetch("job.json")
      .then(res => {
        return res.json();
      })
      .then(res => {
        this.founded = res.items;
      });
  },
  computed:{
      filteredFounded: function(){
          return this.founded.filter((items)=> {
              return items.positionName.match(this.search)
          });
      }
  }
});
    <div class="header">
        <h4>Find Job</h4>
    </div>

    <div id="app" class="nested">
        <div class="card w-50">
            <div class="search">
                <input type="text" class="job" v-model="search" placeholder="Job...">
                <select name="" class="city" id="">
                    <option value="Select">Select</option>
                    <option value="Istanbul">Istanbul</option>
                    <option value="Ankara">Ankara</option>
                    <option value="Izmir">Izmir</option>
                    <option value="Canakkale">Canakkale</option>
                </select>
            </div>

            <div class="find">
                <button>Find!</button>
            </div>

            <div class="card-body" v-for="item in filteredFounded">
                <h5 class="card-title">{{item.companyName}}</h5>
                <p class="card-text">{{item.positionName | to-uppercase}}</p>
                <p class="card-text">{{item.cityName}}</p>
                <p class="card-text">{{item.townName}}</p>
                <p class="card-text">{{item.distance}}</p>
                <a href="#" class=" btn-primary">Go!</a>
            </div>
        </div>
    </div>

    <script src="script.js"></script>

Answer №1

It seems like your issue is as follows:

  • The view updates whenever there is a form change because you have directly linked the `card-body` repeating `div` to the filtering process, rendering the "Find!" button unnecessary.
  • You have overlooked the city selection aspect.

To address these issues, it is recommended to bind a model to the city selector and define separate variables for the JSON data and selected data:

<select name="" class="city" id="" v-model="city">

and:

data: {
  search: "",
  sourceJobs: [],
  selectedJobs: [],
  city: ""
}

Next, populate your JSON data in `sourceJobs` upon creation:

fetch("job.json").then(function (res) {
  this.sourceJobs = res.json();
});

Note that this approach may not be suitable for handling large JSON datasets. In such cases, consider filtering data through a backend API call.

With the form data tied to `data.search` and `data.city`, and job listings stored in `data.sourceJobs`, implement a method (instead of using `computed`) to filter the jobs and store the subset in `data.selectedJobs`:

methods: {
  selectJobs: function () {
    this.selectedJobs = this.sourceJobs
      .filter((job) => {
        return job.cityName === this.city && job.positionName.match(this.search);
      })
  }
}

Lastly, trigger this method when the user clicks the "Find!" button:

<button v-on:click="selectJobs">Find!</button>

If you decide to switch to an API-based filtering approach, simply remove the `created` section and include the API call within the `selectJobs` method.

Additional note: "find/found/found" refers to successfully locating something, while "found/founded/founded" pertains to creating or establishing something like a city or company.

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

Display or conceal certain HTML form elements based on the selection made in the previous form element

I need assistance with a function that can dynamically show or hide certain HTML form elements based on the user's previous selection using JavaScript. For example, if a user selects "Bleached" from the Dyingtype drop-down menu, there is no need to di ...

Slightly puzzled by the declaration of `var app = express()`

After going over the documentation, I'm still struggling to grasp why we store express() inside an app variable. I attempted to call methods using express().get and .post directly, but was unsuccessful. Why is that? Why doesn't it function in t ...

"Retrieve real-time information from the server directly on the client side

Within my express router, I validate the data submitted on a form and then render another page if the data is valid, passing along the form data. My goal is to be able to access this passed data on the client-side. In the chat.ejs view, I have a chatroom.j ...

Effective ways to narrow down data in vuetify v-autocomplete component using Fuse.js

In my application, I am using the Vuetify autocomplete component. This component allows for the use of a custom filter to filter input data. Below is an example of a custom filter for the autocomplete: customFilter (item, queryText, itemText) { const ...

Angular dependency injection function

What is the best placement for the common handleError and handleSuccess functions? These functions are commonly used by every service. Where should these functions be placed? Should they be global functions injected as dependencies? (function () { "u ...

Evaluating the parser for oauth2 implicit grant access_token using javascript

I am currently developing an Angular application that utilizes the implicit grant oauth strategy. In case I do not have a valid access token in my cookies, I am redirected to the web interface of the authentication server where I input my credentials and t ...

Tips for increasing the number of inputs within a form using <script> elements

I am currently working on a form within the script tags and I would like to include additional input fields before submitting. However, the submit button seems to be malfunctioning and I suspect that there may be an issue with how I am accessing it in my c ...

Node is looking for a callback function, but instead received something that is undefined

When attempting to build a basic CRUD app in node js, an issue arises with the error message "Route.get() requires a callback function but got a [object Undefined]" specifically on the router.get("/:id", userController.getUser); line. Routes.js const expr ...

Launching npm using the command "npm run protractor" results in console errors being thrown upon completing the test

Recently, we made the decision to streamline the installation process of Protractor on local machines by specifying it in package.json rather than installing it individually with the -g flag. The addition we made looks something like this: "scripts": { ...

Mixing controllers with the same name in AngularJS from different modules can lead to

Recently, while working on an AngularJS web application with multiple sub-modules, I encountered a situation where two sub-modules had controllers with the same name due to them both having CRUD functionality. Here's a snippet of the code structure: ...

Can select2 and a jQuery Virtual Keyboard work together seamlessly?

Is there a method to implement a jQuery virtual keyboard for inputting into a Select2 select box? The issue is that the dropdown in the Select2 component closes automatically when clicked away from, preventing the use of a web-based virtual keyboard. If ...

The policy of the Authorization Server mandates the use of PKCE for this particular request

I'm currently utilizing the authentication service provided by Hazelbase through next-auth. However, during deployment, an error message pops up stating Authorization Server policy requires PKCE to be used for this request. Please take note that Haze ...

Put a spinner within a JavaScript function

Implementing a spinner using JavaScript function. Hello everyone, I am new to JavaScript and I am struggling to include a spinner in my code. Below is the code that I wrote. Can anyone help me identify what the issue might be? document.getElementById(&apo ...

Limit how API call costs are set in a function by throttling based on an argument

I am currently implementing express-throttle to restrict the number of API calls per IP address each day. I would like to dynamically set the 'cost' parameter in the 'options' array based on a value from the API request (refer to commen ...

Alternate the color over time using CSS

Is there a way to dynamically change the color of a div from black to white every two seconds, and then from white to black, continuously toggling as long as the div is visible? Essentially, I want the div to only be displayed when a user clicks and drag ...

Repetitive attempts have led to the cancellation of the AJAX and PHP petition statuses

Whenever I click the button, I am trying to update a MySQL table using AJAX jQuery. Unfortunately, I am encountering a problem where the AJAX jQuery does not work properly sometimes. It starts off fine, but after a certain number of attempts, it stops work ...

Creating dynamic qtip2 tooltips is an effective way to enhance user interaction on

I am facing an issue where all tooltips work perfectly fine when the page loads, but stop working after data refreshes through ajax. How can I resolve this problem? $(document).ready(function() { // MAKE SURE YOUR SELECTOR MATCHES SOMETHING IN YOUR HT ...

What is the correct way to define the field name in the update() function of Mongoose?

When attempting to update every field contained in the dataToChange object, I encountered a problem where the update() method does not take the key name from the outside. Instead, it looks for a "key" field within the database's object. How can I work ...

When trying to pull a component from Svelte, I receive an error message stating "Selection Range

I'm still relatively new to svelte, so I might be handling things incorrectly. Whenever I attempt to separate my button component, regardless of whether I name the component ./Button.svelte, ./Button, Button.svelte, or try variations with capitalizat ...

Insert fresh user information into the div

Learning JavaScript is a challenge I'm tackling. I have a question that may seem trivial, but any assistance would be greatly appreciated. I currently have this code: Javascript <script type="text/javascript"> function fn(){ var Name = ...