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

transfer to a different outlet when needing to circle back earlier

I'm currently working on implementing validation in a form, and one of the needed validations involves retrieving a value from an input field and checking its existence on the server or in a JSON file. However, there seems to be a problem where even ...

Steps to assign the identifier as the current index in the v-for iteration

Struggling to assign the id based on the index of a v-for loop. I attempted: <li v-for="(item, index) in items" v-bind:key="item.id"> <p>{{item.name}}</p> <input id= {{index}} type= "number"> < ...

Verify the type of email domain (personal or corporate)

Here's an example: isPersonalEmail("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c0aea1ada580a7ada1a9aceea3afad">[email protected]</a>") // true isPersonalEmail("<a href="/cdn-cgi/l/email- ...

In JavaScript using Vue.js, you can compare various objects within an array and calculate the total sum of their values based on a shared

This task may pose a challenge for those new to programming, but seasoned developers should find it relatively simple. I've been searching for a solution without success so far, hence turning to this platform for help. Here's the scenario at han ...

Accessing Elements by Class Name

I've been searching for information on the capabilities of getElementsByClassName for hours. While some sources mention it returns an HTML collection of items, length, and named items, w3schools provides an example where innerHTML is utilized: var x ...

Unit tests are successful, but an error occurs stating "headers cannot be set after they have been sent."

Currently, I am working on writing unit tests for the API endpoints of my very first express app. I am using a data structure as a placeholder for a database and all the tests are passing successfully. However, I encountered an error in the console stating ...

Angular JS Sorting Wordpress Plugin allows users to easily organize and sort content

Seeking some assistance here, any help would be greatly appreciated. Currently using a Wordpress Angular JS plugin that is causing some unusual alphabetical sorting. This snippet of code showcases the taxonomy: <!-- for taxonomy --> <div ng-if ...

Users are reporting that verification emails are not being sent when the Accounts.createUser function is used within

I have a simple meteor method set up to create user accounts. In my server/methods.js file: Meteor.methods({ createUserAccount: function(user) { return Accounts.createUser(user); } }); Then in my server/init.js file: Meteor.startup(function() ...

Guide to utilizing a JWT token within an httpOnly cookie for accessing a secured API endpoint

Utilizing next.js and next-auth for user login authentication with an API. Once the login is successful, a httpOnly cookie named __Secure-next-auth.session-token is stored in the browser. The following is a sample value (not actual data): eyJhbGciOiJIUzUxM ...

Utilizing MVC architecture and AJAX for seamless form submission

Recently, I delved into exploring MVC on the client side using JavaScript (JavaScript MVC). While everything seemed promising at first, I hit a roadblock when it came to form submissions. The View part couldn't handle it easily. The event is attached ...

Unveiling the Magic: Enhancing Raphaeljs with Interactive Click Events on a Delicious Slice of the

I'm having trouble responding to a click event on each slice of a Raphael Pie Chart. I've tried implementing the code below, but it doesn't seem to be working. The code is just two lines, commented as "My Code", in the example from the offic ...

Is it possible to increment an integer value in jQuery after obtaining the sum result?

Actually, I'm trying to extract the integer value from my input field. For example, if I enter the value 4+5, I want to display the result as 9 in a separate div. However, instead of getting the expected result, I am receiving [object Object]. I&apo ...

Using Vue JS to handle image upload with "PROP MUTATING"

Apologies for any language barriers or inaccuracies in my English. I have a single component designed specifically for image uploads. It is currently being utilized in two forms: an add form and an edit form. In the edit modal, the Image URL is passed as ...

Manipulating nested lists in Vuejs by removing elements

After reading about how to remove elements from lists in VUEJS on Stack Overflow, I came across various methods like this.$remove, splice, and this.$delete. I was curious about applying these methods to a nested loop structure in my code which goes three l ...

Looping through values in VueJS from 100 to 0

I am currently working on creating a power meter that will smoothly transition from 100 to 0 and back again to 100. The idea is for the user to press a button, causing the meter to stop at a random value. I just need some assistance in getting the loop fu ...

Incorporating Ruby on Rails: Sending a fresh POST request to API and instantly

I'm a beginner in the field of ruby on rails. Our website allows users to search and receive a list of results. Now, I want to incorporate sorting functionality for the results (by price, rating, etc). The API handles the sorting process, so all I ne ...

My stored variable in the php session is not being recalled properly

Currently, my PHP script is generating new files based on user input. I want all documents to be created using the initial input to ensure consistency. In the first PHP script, I set the variable as follows: session_start(); $_SESSION["FirstName"] = $_POS ...

Obtain element values using Protractor and WebDriverJS and store them in an array of objects

Coming from a Java+WebDriver background, I am new to Protractor, WebdriverJS, and Jasmine. In the image displayed, my goal is to hover over all bubbles and retrieve the tool tip values (city, sold, connected), assign them as objects to an array, and return ...

Display or conceal form elements depending on the JSON response

Upon making an api call, a json Response is received with the following structure: {"Field":"Amount","FieldName":"Amount","FieldType":"Numeric","MaximumLength":128,"MinimumLength":0,"Options":"Mandatory"} This api call yields between 5-10 of these object ...

Issue with Bcrypt comparison resulting in constant false output

Attempting to implement password verification using bcryptjs, const bcrypt = require('bcryptjs'); login(post){ this.uid = post.uid; this.pin = post.pin; this.getUser(this.uid); if(this.checkUser != undefined ...