Vue search button not returning results

Hello, this is my HTML file.

<div id="app1" v-cloak>
        <input v-model="term" type="search">
        <button @click="search">Search</button>
        <p/>
            <div v-for="post in posts" class="post">
                    <p><strong>@{{post.title}}</strong></p>
                    <p>@{{post.body}}</p  
                    <br clear="left">
                </div>
</div>

This is my app.js file:

const app1 = new Vue({
    el:'#app1',
    data:{
        term:'',
        posts:[],
        noResults:false,
        searching:false
    },
    methods:{
        search:function() {
        const url = `http://jsonplaceholder.typicode.com/posts/${encodeURIComponent(this.term)}` ;
            fetch(url)
            .then(res => res.json())
            .then(res => {this.posts = res.posts;})
        }
    }
  });

I need help with ensuring that when the search button is pressed with a value, the search results are appended to the post class. The Chrome Dev Tools show that the results are correct, but they do not display on my page. How can I achieve this?

Answer №1

Your final line needs to be:

.then(posts => this.posts = posts)

const app1 = new Vue({
  el:'#app1',
  data: {
    term:'',
    posts:[],
    noResults:false,
    searching:false
  },
  methods:{
    search: function() {
      const path = `http://jsonplaceholder.typicode.com/posts/${encodeURIComponent(this.term)}` ;
       fetch(path)
        .then(res => res.json())
        .then(posts => this.posts = posts)
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app1" v-cloak>
 <input v-model="term" type="search">
 <button @click="search">Search</button>
 <p/>
    <div v-for="post in posts" class="post">
      <p><strong>@{{post.title}}</strong></p>
      <p>@{{post.body}}</p>  
      <br clear="left">
    </div>
</div>


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

Why is it that my React app is on a different port than the Express server that it listens to?

As I'm working on my React app, it currently runs on the default port http://localhost:3000/. However, when I need to communicate data from the client to the server, I have to listen on a different port. Take a look at the below code snippet: const ex ...

Filtering data in AngularJS by parsing JSON records

I have a JSON file containing restaurant information and I need to display the data by grouping them based on their respective address fields. For example, all restaurants with the address 'Delhi' should be shown first, followed by those from &ap ...

Developing a user-friendly widget for a website that is not optimized for mobile devices

Here's the backstory: I'm currently in the process of creating a mobile-friendly widget for my clients. Unfortunately, they have web pages that are not optimized for mobile devices, and it doesn't seem like that will change anytime soon. Th ...

Utilizing the fetch method for sending cross-origin JSON data to an Express backend

When attempting to use Fetch to send JSON data from a form and receive a response from an Express server, I am encountering an issue where I only see an empty object in the console instead of the expected JSON response with the form values. You can find t ...

Using a for loop, how can the property value be set in another object?

One challenge that I am facing is setting object property values. The object in question looks like this: const newPlan = { name: '', description: '', number: '', monday: { breakfast: '', ...

Prevent typing in text box when drawer is activated by pressing a button

update 1 : After removing unnecessary files, I need assistance with https://codesandbox.io/s/0pk0z5prqn I am attempting to disable a textbox. When clicking the advanced sports search button, a drawer opens where I want to display a textbox. The toggleDra ...

Refreshing jQuery via Ajax Response

In our JSF2 application, we encounter situations where we need to re-invoke the JavaScript (specifically jQuery for UI styling) when making Ajax calls. However, it seems that the JavaScript functions are not being called upon receiving the Ajax response fr ...

The origin of the recipient window does not match the target origin provided when using postMessage on localhost

Currently, I am in the process of developing an application that utilizes single sign-on (SSO) for user authentication. Here is a breakdown of the workflow: Begin by launching the application on localhost:3000 (using a React Single Web Application). A po ...

Tips for incorporating Bootstrap classes into a React project, setting the className attribute to an empty string

After setting up Bootstrap and Create-React-App using npm on my local machine, I proceeded to create a new React app. The first component I worked on was counter.jsx: import React, { Component } from 'react'; class Counter extends Component { ...

Preventing Broken URLs in Jquery each

What is the best way to prevent taking images with broken URLs? jQuery.each(jQuery('img'), function(index, obj) { imageStack.add(jQuery(obj)); }); ...

How to Toggle the "active" Class Among Child Elements in vueJS 2

I'm interested in learning how to implement this functionality using vue.js. Currently, I am able to toggle the active class on a single item, but when I click on another item, the active class remains on the previous item. Here is my current setup: ...

Tips for finding the index of data in Cesium

After successfully completing the tutorial on building a flight tracker, I am facing a challenge. I want to access the current index of my data at any given time while my app is running cesium and displaying the airplane animation following the flight path ...

Calculating the total of fields from populated documents using Mongoose

In my application, I have two main models: User and Track. A User can complete various Tracks and earn points for each one. The schema for the User model looks like this: let userSchema = new mongoose.Schema({ name: {type: String, required: true}, ...

Leveraging JavaScript to generate a downloadable PDF document from the existing webpage

My goal is to have the user click a button labeled 'View PDF' or 'Download PDF' on the current webpage. This button would then execute JavaScript code to generate a PDF based on how the current page appears. I attempted using jspdf for ...

ajax receives an empty responseText after sending intermediate data to Python on the backend

Initially, the frontend passed an identification to the backend. The backend utilized this identification to retrieve data from the database. The extracted data then underwent additional processing on the backend before being sent back to the frontend. Be ...

Special characters like greater/less than signs have not been properly encoded

I am currently facing an issue in regards to escaping strings on the server side (using Node.js & Express.js) that contain greater/less than signs (<, >). Below is the code snippet I'm using on the server side: socket.on('message', fu ...

What is the best way to transmit a modified variable from a client to a server using the fetch API?

I'm facing a challenge in sending a modified variable from the client to the server and utilizing it in main.ejs. Here's my current code: <script> document.getElementById("char2btn").addEventListener("click", change) fun ...

Access the id of an object in an array using Vue.js

Is there a way to showcase value data depending on the index array? I have created a modal for editing data, with a JSON structure like this: [ { "ID": 3, "idusers": 3, "skills": "Go", ...

Interactive HTML and PHP form designed to compute and display the result of a straightforward mathematical equation

I'm looking to add a dynamic HTML/php form on my webpage that can solve the following formula instantly without any page refresh. I am confused about the best approach and the code required to make it happen. The formula I want to implement is as fol ...

Position divs to be perfectly aligned and centered

I'm in the process of creating a webpage and facing challenges with aligning my divs properly, specifically the animated company logos. I want them to be positioned side by side rather than on top of each other, with space in between to fit the layou ...