Dynamic content updates in Vue.js for div elements

As I venture into the world of developing a Single Page Application (SPA) using Vue.js, I find myself facing a steep learning curve due to my limited knowledge on the subject. Despite following a tutorial and managing to get something up and running, I still consider this task to be relatively simple!

My goal is to create a basic page that accomplishes the following:

  • Makes a REST API call to fetch some JSON data
  • Displays a list with links of a specific field from the retrieved results on the left side of the screen

(So far, so good)

Now, I wish to implement a feature where clicking on one of the links will reveal the value of another field corresponding to the same record on the right side of the screen.

For example, let's assume the JSON data looks like this:

{
   "jokes": [
      {"setup":"setup1", "punchline":"punchline1"},
      {"setup":"setup2", "punchline":"punchline2"},
      {"setup":"setup3", "punchline":"punchline3"}
   ]
}

On the screen, I envision seeing:

setup1
setup2
setup3

Thus, clicking on setup1 will display punchline1, setup2 will show punchline2, and so forth.

Below is my current code snippet - specifically aimed at displaying the punchline in the moduleinfo div. While acknowledging the existing solution doesn't function as intended, I have scoured for similar examples without much success. Any guidance or pointers would be warmly welcomed.

<template>
  <div class="home">
    <div class="module-list">
      <input type="text" v-model.trim="search" placeholder="Search"/>
      <div>
        <ul>
          <li class="modules" v-for="value in modulesList" :key="value.id">
            <a href="#">{{ value.setup }}</a>
          </li>
        </ul>
      </div>
    </div>
    <div class="moduleinfo">
      <h2>Module info</h2>
      <!-- <p>{{ value.punchline }}</p> -->
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'Home',

  data: function(){
    return {
      jokes: [],
      search : ""
    }
  },

  mounted() {
    this.getModules();
  },

  methods: {
    getModules() {
      var self = this

      const options = {
        method: 'GET',
        url: 'https://dad-jokes.p.rapidapi.com/joke/search',
        params: {term: 'car'},
        headers: {
          'x-rapidapi-key': '...',
          'x-rapidapi-host': 'dad-jokes.p.rapidapi.com'
        }
      };

      axios.request(options)
        .then(response => {
            self.jokes = response.data;
            console.log(response.data);
        }).catch(function (error) {
          console.error(error);
      });
    }
  },

  computed: {
    modulesList: function () {
      var jokes = this.jokes.body;
      var search = this.search;

      if (search){
        jokes = jokes.filter(function(value){
          if(value.setup.toLowerCase().includes(search.toLowerCase())) {
            return jokes;
          }
        })
      }
      return jokes;
    }
  },
};
</script>

Thank you for any assistance!

Answer №1

When I was working on a Single File Component for my Vue 2 CLI project, I found that Ryoko had already provided an answer using the same approach I was going to suggest. The solution involved adding a new property to keep track of displaying the punchline.

Even though I had already created the component, I decided to share it anyway. My version changes the layout by using a table instead of a list, but the core functionality remains intact.

<template>
  <div class="joke-list">
    <div class="row">
      <div class="col-md-6">
        <table class="table table-bordered">
          <thead>
            <tr>
              <th>SETUP</th>
              <th>PUNCHLINE</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(joke, index) in jokes" :key="index">
              <td>
                <a href="#" v-on:click.prevent="getPunchline(index)">{{ joke.setup }}</a>
              </td>
              <td>
                <span v-if="joke.showPunchline">{{ joke.punchline }}</span>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        jokes: [
          {
            setup: "setup1",
            punchline: "punchline1"
          },
          {
            setup: "setup2",
            punchline: "punchline2"
          },
          {
            setup: "setup3",
            punchline: "punchline3"
          }
        ]
      }
    },
    methods: {
      getPunchline(index) {
        this.jokes[index].showPunchline = true;
      },
      addPropertyToJokes() {
        // Ensure the new property is reactive
        this.jokes.forEach( joke => this.$set(joke, 'showPunchline', false) );
      }
    },
    mounted() {
      this.addPropertyToJokes();
    }
  }
</script>

Answer №2

If you want to add a new property within the data object and create a method that sets it when clicking on the <a> tag, you can refer to the example code below. It's an edited version of your current solution, with the added feature highlighted for easy identification.

The select method is designed to insert the selected joke object into the selectedJoke variable, allowing you to display it beneath Module Info.

Since the default value is null, which can also be undefined, make sure to use v-if to check whether there is a value present or not. This will prevent any errors from popping up in the console.

<template>
  <div class="home">
    <div class="module-list">
      <input type="text" v-model.trim="search" placeholder="Search"/>
      <div>
        <ul>
          <li class="modules" v-for="value in modulesList" :key="value.id">
            <a href="#" @click.prevent="select(value)">{{ value.setup }}</a>
          </li>
        </ul>
      </div>
    </div>
    <div class="moduleinfo">
      <h2>Module info</h2>
      <p v-if="selectedJoke">{{ selectedJoke.punchline }}</p>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'Home',

  data() {
    return {
      jokes: [],
      search : "",
      selectedJoke: null,
    }
  },
  methods: {
    select(joke) {
      this.selectedJoke = joke;
    },
  },
};
</script>

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

The installed version of Chromedriver is newer than the current version

Currently, I am utilizing Selenium for end-to-end tests with jest. My browser of choice is Chrome version 85.0.4183.121, and the correct chromedriver version is present in my PATH. When I execute chromeversion -v in the command line, it returns ChromeDriv ...

Testing API route handlers function in Next.js with Jest

Here is a health check function that I am working with: export default function handler(req, res) { res.status(200).json({ message: "Hello from Next.js!" }); } Alongside this function, there is a test in place: import handler from "./heal ...

Utilizing and organizing a collection of JSON objects in a React application

I am attempting to iterate through the following array: { "videos_json": [ { "id": "Student 1", "video": "VIDEO TO BE PLAYED", "title": "first class", "mater ...

Is there a way to direct URLs with varying "levels" in Express?

I am in the process of learning the MEAN stack and developing a tool within my API that can multiply a series of numbers. I have encountered two questions that the Express Documentation did not address. What is the best way to route URLs of varying depth? ...

Unable to style Vuetify components with CSS

I am currently following along with this tutorial and I have reached the part where Vuetify is being added. Despite matching my code to the tutorial, Vuetify does not seem to load on my end. In the comparison image below, the left side shows how it appear ...

Storing a JSON data structure in a file in Node.js

I have searched for similar questions on this topic but have not found a solution. My task involves converting a CSV xml file to a json array of objects. The function provided below successfully accomplishes this: const csvtojsonV2 = require("csvtojson" ...

Extracting the name of a track from the /r/listenToThis subreddit for an IFTTT automation script

I have a list of songs gathered from this subreddit, presented in the following format: [ "Lophelia -- MYTCH [Acoustic Prog-Rock/Jazz] (2019)", "Julia Jacklin - Pressure to Party [Rock] (2019)", "The Homeless Gospel Choir - I'm Going Home [Folk ...

Ways to configure NewtonSoft.Json.JsonConvert to serialize an enum as a string instead of an integer

At this moment, I am working with a class named "foo" which has the following structure: public class foo { public MyEnumType Result { get; set; } } When I create a new instance of this class and serialize it using JsonConvert as shown below: foo a ...

What is the process for generating a watermark directive in angularjs?

My application utilizes a jQuery script for watermarking textboxes. I created a directive to easily apply this watermark to input elements, but it's not functioning as expected. While debugging, I can see the watermark being added, but once the UI fin ...

Use a JSON file to dynamically define the file path for static assets in the index.html file of a React application

I am working on a solution to dynamically modify the file paths of static files (js & css) in the index.html file within my create-react-app. My goal is to have these paths directed to different sub-directories based on settings specified in a settings.jso ...

Limiting the number of promises in AngularJS

My web application allows users to select multiple files using a file input. After the user selects the files, I upload them one by one through my REST API. However, in Internet Explorer, if the user selects more than 10 files at once, some of the requests ...

Having difficulty fetching custom datatype JSON data in Swift

I am experiencing some difficulties with this code that is supposed to download JSON data, parse it, and return the information. When I print the info, everything looks good, but when it is returned, the struct defaults are returned instead. I'm unsur ...

ability to reach the sub-element dictionaries in typescript

class ProvinciaComponent extends CatalogoGenerico implements OnInit, AfterViewInit { page: Page = new Page({sort: {field: 'description', dir: 'asc'}}); dataSource: ProvinciaDataSource; columns = ['codprovi ...

json data hidden from sight in jQuery

Snippet of HTML Code: <select name="ser" id="ser" class="form-control" onchange="getPrice(this.value);"> <option value="">--Select--</option> <option value="Value11">Value1</option> <option value="Value2">Value2</op ...

Tutorial on implementing a _variables.scss file for Vue components with sass-resource-loader on Vue CLI 3.04

In my VueJs project created with the Vue CLI 3.0.4, I am aiming to utilize SCSS variables across all components without the need to import _variables.scss into each one individually. After some research, I found that I can achieve this using sass-resource- ...

Imitate a hover effect

In my list, I have images and descriptions set up in the following format: <li> <img class="photography" src="PHOTO/boat.jpg" alt="Boat on sea." /> </li> <li><div id="description" class="description"> <p>BOAT</p> ...

Tips for including two values at the same index in a map array

let wordsArray; let indexArray = []; let index; let myMap = new Map(); const Storage = function(userInput){ wordsArray = userInput.split(' '); //remove ',' and '.' for( let i = 0; i < wordsArray.length ; i ...

Endless redirect loop generated by JavaScript Facebook OAuth integration

To ensure users have the necessary permissions for my app, I plan to redirect them to the oauth page if any required permissions are missing. However, when attempting to redirect from the FB.api callback function with the code below, I seem to encounter a ...

use dotenv in your Build Folder

Is it possible to have my .env file in my React JS project move to the build folder when I run NPM build command? If so, how can this be achieved? If not, what would be the alternative solution? I attempted using "build": "cp .env.template ...

When using the CDN import version, React does not render components or code

Unfortunately, I am unable to progress with studying React due to encountering a basic issue. Please excuse my lack of experience, no need to judge harshly. The message is not displaying, although the code itself is straightforward; I am perplexed as to wh ...