2

i have an array of objects with first name and last name inside of it. How can i toggle between the first name and last name 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 switch between first and Last names</button>  
</div>
</template>

I am still trying to get my head wrapped some of the basic concepts of vuejs so please excuse any naive questions. Thank you.

1 Answer 1

2

You can set new variable and set what to see:

<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>

And in data() just add variable showLastName like:

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

This should work.

Good luck!

Sign up to request clarification or add additional context in comments.

1 Comment

I see and if i wanna do this using the vuex store, would the onclick be a mutation?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.