How can Vuejs switch between different attributes of an object?

How can I switch between first name and last name in an array of objects on a button click?

new Vue({
  el: '#app',
  data() {
    return {
      myArray: [{
          firstName: 'ricky',
          lastName: 'martin'
        },
        {
          firstName: 'tony',
          lastName: 'Montana'
        }
      ]
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<template>
<div>
<button>Click me to toggle between first and last names</button>  
</div>
</template>

I am still trying to understand some basic concepts of vuejs, so please bear with me. Thank you.

Answer №1

To display different names based on a variable:

<template>
    <div v-for="item in myArray">
         <div v-if="showLastName">
             {{item.lastName}}
         </div>
         <div v-else>
             {{item.firstName}}
         </div>
    </div>
    <div>
        <button @click="showLastName = !showLastName">
           Click me to switch between first and Last names
        </button>  
    </div>
</template>

In your data() method, include the showLastName variable:

data() {
    return {
      showLastName: false,
      myArray: [{
          firstName: 'ricky',
          lastName: 'martin'
        },
        {
          firstName: 'tony',
          lastName: 'Montana'
        }
      ]
    }
  }

This solution should be effective.

Best of luck!

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

Is there a way to ensure that my JavaScript code remains permanent?

Is there a way to have the website remember the user's theme preference between visits? For example, if they choose the dark theme, can it automatically be loaded the next time they access the site? This is my current javascript code for handling the ...

Encountering a problem while trying to run npm publish with public access, error code E

I've encountered an issue when attempting to publish a scoped package on npm, where I consistently receive this error via the CLI: npm ERR! code E403 npm ERR! 403 403 Forbidden - PUT https://registry.npmjs.org/@username%2fdynamic-ui-elements - Forbidd ...

Spin an object around the global axis using the tween.js library

I'm trying to achieve a gradual rotation of a cube on the world axis using tween. Initially, I was able to rotate the cube around the world axis without tweening with the following code: rotateAroundWorldAxis(cube[1], new THREE.Vector3(0,1,0),degreeT ...

Issues arising post transitioning to 14.0.0 from 13.0.0 version of ngx-masonry library leading to failed tests

Following the update to the latest stable version of the library ngx-masonry 14.0.0, our tests started failing. The release was just yesterday (24.10.2022) and you can find the changelog here: https://github.com/wynfred/ngx-masonry/blob/master/CHANGELOG.md ...

Troubleshooting problems with connecting Express JS and MongoDB

I've written a simple code to connect express js to mongodb, and I've installed both packages. However, I'm encountering an error. Can someone help me troubleshoot this? const express = require("express"); const app = express(); app.listen( ...

Is there a way for me to verify if a dynamic element has an array property with a specific value within its child element?

Seeking assistance to optimize my code and improve my function for a sequence quiz. The objective is to arrange the answers in the correct order and then use a check answers function to validate. The quiz questions are stored in an array, with each answer ...

Tips for making an AJAX request using jQuery

I have a new project that involves collecting user data and displaying it on the same page. I was able to successfully implement an Ajax call using JavaScript, but now I want to transition to using jQuery. Below is my JavaScript code: var output1 = docum ...

Expanding and collapsing a div using jQuery when an image is clicked

I have a query that spans across two areas - CSS styling and JQuery functionality. The primary concern I have is related to my code snippet below. When the user clicks on the circular profile image, ideally, the "profiledrop" div should become visible. ...

Unable to locate the accurate information

Every time I run the cycle, there should be a match with the specified parameters and the message "OK" should appear. However, I am always getting a result of "No". request( { url: 'http://localhost:5000/positions/get', metho ...

Guide to building a fast search feature similar to Google using JSP and servlets

Currently, I am developing a simple instant search feature that searches the database and immediately displays results, similar to Google Instant. I came across an article on implementing this feature at . However, I am curious to know if it's possibl ...

JS Not activating when clicked

I'm attempting to activate the function call_ajax_add_to_quotelist by using a button with the code below: $cartlink .= '<a class="add_to_cart button alt" href="javascript:void(0);" onclick="call_ajax_add_to_quotelist(add_to_quotelist_ajax_url ...

Multiple file uploads are causing the issue of req.file being undefined

After going through all the suggested solutions, I am still struggling to identify the root cause of my issue. The problem arises when trying to upload multiple files and form inputs - the req.file is always undefined and the image data ends up in the req. ...

What is the best way to generate a universal API URL that can be utilized in all components for both AJAX post and get requests in Vue3 without relying on axios?

Is there a way to centralize the 'https://myapp/' prefix for all request URLs? $.get({ url : 'https://myapp/' + 'dashboard/', data: JSON.stringify({ date: fromDate, }), success: function(response){ ...

My code includes a function that uses setInterval to generate graphs

Is there a way to stop the setInterval function without causing the graph to disappear? I've noticed that when the setInterval stops, the last 7 points plotted on the graph disappear. How can I prevent this from happening? Any suggestions would be gre ...

What is the best way to manage zoom settings following a completed search query?

Whenever I try to search for an address using this map, it zooms in way too much making the map unusable. Despite my efforts to adjust the map bounds, I have not been successful. It seems like I am on the right track but for some reason, it just isn't ...

leveraging socket.io alongside express router

As someone who is relatively new to node.js, I am currently in the process of creating a webchat application. My project consists of a server.js file and a router.js file where I have defined all my routes. Unlike many others, I am not using express-genera ...

Why does the getter consistently generate the previous value?

Check out this code snippet: function User(fullName) { this.fullName = fullName; Object.defineProperties(this, { firstName: { get: function () { return fullName.split(" ")[0]; ...

Personalized HTML Input Field for Digital Keyboard Scores

As a new JavaScript beginner, I have experimented with various approaches in an attempt to create a website that features a digital piano experience without the actual instrument. My goal is to develop a platform where pressing multiple keys together will ...

Converting PHP JSON data to a JavaScript variable

Before asking this question, I tried all possible solutions found on Google and here on Stack Overflow. In my JavaScript file, I currently have: var locations = [ ['Name','Country','City','lat','lng'] ...

The information being transferred from a jQuery Ajax request to an MVC ApiController Action is disappearing

Let me first mention that although there are similar questions to this one already posted here, I've tried all the solutions and have not had any success. I have an MVC ApiController Action with the following signature: public void Post([FromBody] E ...