Updating switch data on click using Vuejs: A step-by-step guide

Could someone please explain to me how to swap two different sets of data when clicked?

For instance, let's say we have the following data:

data() {
        return {

          data_one: [
            {
              name: "Simo",
              age: "32"
            }
          ],

          data_two: [
            {
              name: "Lisa",
              age: "25"
            }
          ],

        }
      },

I would like to display this data using v-for, and have two buttons that allow switching between data_one and data_two, with data_one displayed by default.

<button @click="change_to_data_one">Data 1<button>
<button @click="change_to_data_two">Data 2<button>

<li v-for="item in data_one">{{item.name}} - {{item.age}}<li>

Answer №1

Consider implementing a computed property:

new Vue({
  el: "#demo",
  data() {
    return {
      data_one: [{name: "Simo", age: "32"}],
      data_two: [{name: "Lisa", age: "25"}],
      selected: "data_one"
    }
  },
  computed: {
    showData(){
      return this[this.selected]
    }
  },
  methods: {
    swap(val) {
      this.selected = val
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <button @click="swap('data_one')">Data 1</button>
  <button @click="swap('data_two')">Data 2</button>
  <ul>
    <li v-for="(item, i) in showData" :key="i">{{item.name}} - {{item.age}}</li>
  </ul>
</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

Node.js program closes immediately upon Java startup

I am building a Discord bot that features a Java FXML interface and utilizes a Node.js program to function as an Audio playing bot. However, I am encountering an issue where the process for Node.js closes immediately when opened in Java. The problem arise ...

Switch off any other currently open divs

I'm currently exploring a way to automatically close other div's when I expand one. Check out my code snippet below: $( document ).ready(function() { $( ".faq-question" ).click(function() { $(this).toggleClass('open'); $(this ...

What is the best way to incorporate bullet points into a textarea?

How can I make a bullet point appear when pressing the 'enter' button inside a textarea? I tried using this code, but it doesn't seem to work. Any suggestions? <script> $(".todolist").focus(function() { if(document.getElementById( ...

Tips for creating an auto-incrementing ID within Firebase's real-time database

How can I create an automatic incrementing ID for entries in a Firebase database? The first item should have an ID of 1, and the second one should be 2. var database = firebase.database(); var userDetails = database.ref("Article"); userDetails. ...

The query parameter is not defined in the router of my Next.js app API

I'm currently working on building an API endpoint for making DELETE requests to remove albums from a user's document in the MongoDB Atlas database. Struggling with an error that keeps popping up, indicating that the albumName property is undefin ...

What is the best way to merge arrays within two objects and combine them together?

I am facing an issue where I have multiple objects with the same properties and want to merge them based on a common key-value pair at the first level. Although I know about using the spread operator like this: const obj3 = {...obj1, ...obj2} The problem ...

What is the best way to swap out an array with a new array in Vue?

Every 10 seconds, I am querying my database for the latest fire calls. When I use app.events = data.calls, the data does not refresh. I initialize the data with the same function that is called every 10 seconds and I can see the table. How do I replace a ...

Trouble rendering Bootstrap dropdown in Vue2 component

I am experiencing a peculiar issue with my Vue child component, which is responsible for displaying a bootstrap modal and includes several fields, including one that should show a dropdown selection. Strangely, the dropdown button fails to activate, result ...

"Utilize jQuery to load a file when hovering over a specific

How can I dynamically load an external file using jQuery when a user hovers over a specific div? I attempted to load the file like a CSS file on hover but was unsuccessful. Is it possible to load a CSS file on hover as I've seen in some examples? $(d ...

How to dynamically add a form to your website

Looking to dynamically insert a form on a page based on the value selected from a datalist, all without having to reload the entire page. <form action='#' method='get'> <input list="category" name="category"> <da ...

Understanding the reading of Java Class List in Vue Js

As a beginner in Front-end development, I am trying to figure out how I can use Vue.js to read a Java class List. Specifically, I have a Java class that includes a list of fruits and I want to be able to display this list on the UI using Vue.js: public c ...

When sorting in AngularJS using the orderBy filter, remember that string values should come before numeric values: for example, sort as follows (n/a, 0,

While running an AngularJS filter sorting on a table, I encountered an issue where if the value is 'n/a' (which is a numeric string), the sorting is incorrect. I expected the order to be n/a, 0, 1, 2, 5, 100 since strings should be considered l ...

Is it possible to view newly added text in real-time on a separate client in Node.js without relying on socket.io?

I am in the process of creating a straightforward web application where users can input phrases. The app works fine, except for one issue - it doesn't display new additions from other users instantly. I am aware that socket.io could solve this problem ...

The function Sequelize.create() does not exist

My attempts to push my DB with sequelize are not working, even though I have set up this schema for the DB: module.exports = (sequelize, DataTypes) => { const Problems = sequelize.define("Posts", { theme: { type: DataTypes.ST ...

Modify all the content within the DIV using Regex, while keeping the HTML tags intact

I am attempting to replace all the text inside a DIV, including within its children, without modifying any HTML tags. Specifically, I want to switch all instances of 'Hello' to 'Hi'. Thank you for your help. var changes = $('div ...

What is the method for identifying modules that rely on a specific module?

Is it possible to view all dependencies modules of a specific module, similar to this: npm-remote-ls <module-name> But how can we see the modules that depend on a particular module? Any help would be appreciated. Thank you. ...

Exploring JSON data in AngularJS

After creating a new Angular App, I decided to store some data in a JSON file. My main concerns are where to best store the .json file within the app and how to access it. Currently, I am facing this error in my Chrome console: GET http://localhost:8000/t ...

The intervals in hooks seem to be malfunctioning and not updating the date and time as expected

I am trying to continuously update the date and time every minute using React hooks. However, I am facing difficulty in updating the time properly. const Link = (props) => { let date = new Date(); const [dateTime, setDateTime] = useState({ cu ...

Different ways to resize an image in various sizes without relying on PHP thumb

I have developed an admin panel for managing reservations of charter, yacht and other vehicles. I am looking for a solution to upload only one image per vehicle and resize it in multiple sizes without relying on the phpthumb library due to its slow loadi ...

Remove attributes from a collection of objects

Here is an array of objects: let array = [{ firstName: "John", lastName : "Doe", id:5566, weight: 70 },{ firstName: "Francis", lastName : "Max", id:5567, weight: 85 }]; I am looking to remove the properties "lastName" and "weight" for all obj ...