Display tab content in Vue.js upon clicking

I'm encountering an issue with my Vue.js code. I want to display specific content every time I click on a tab.

Here's the code snippet I have written:

<template>
  <nav class="horizontal top-border block-section">
    <div class="col-md-20" id="tabs">
       <a href="#" id="overview" class="col-md-2" @click="active">Overview</a>
       <a href="#" id="aboutcompany" class="col-md-2" @click="active">About Company</a>
  </nav>

  <div id="over" class="show">
      <overview></overview>
  </div>
  <div id="about" class="hide">
      <about-company></about-company>
  </div>

</template>

<script>
import Overview from './Overview'
import AboutCompany from './AboutCompany'

export default {
  components: {
  Overview,
  AboutCompany
},
methods: {
  active(e) {
     e.target.id.addClass('show');
  }
}
}
</script>

When I click on the "About Company" tab, I expect the

element to have the class "show" and for the
element to have the class "hide".

Answer №1

If you want to maximize the capabilities of vuejs, consider using the following code:

<template>
  <nav class="horizontal top-border block-section">
    <div class="col-md-20" id="tabs">
      <a href="#" v-for="tab in tabs" @click.prevent="setActiveTabName(tab.name)">
        {{ tab.displayName }}
      </a>
  </nav>

  <div v-if="displayContents(activeTabName, 'overview')">
      <overview></overview>
  </div>
  <div v-if="displayContents(activeTabName, 'about')">
      <about-company></about-company>
  </div>
</template>

<script>
import Overview from './Overview'
import AboutCompany from './AboutCompany'

export default {
  components: {
  Overview,
  AboutCompany
  },
  data() {
    return {
      // Specify all available tabs here
      tabs: [
        {
          name: 'overview',
          displayName: 'Company Overview',
        },
        {
          name: 'about',
          displayName: 'About us',
        }
      ],
      activeTabName: null,
    };
  },
  mounted() {
    // Set the first tab as active by default
    this.activeTabName = this.tabs[0].name;
  },
  methods: {
    setActiveTabName(name) {
      this.activeTabName = name;
    },
    displayContents(name) {
      return this.activeTabName === name;
    },
  },
}
</script>

Answer №2

If you want to avoid using a separate function, you can simply make use of a data variable.

  <nav class="horizontal top-border block-section">
    <div class="col-md-20" id="tabs">
       <a href="#" id="overview" class="col-md-2" @click="activeTab = 'OVER'">Overview</a>
       <a href="#" id="aboutcompany" class="col-md-2" @click="activeTab = 'ABOUT'">About Company</a>
  </nav>

    <div id="over" class="{show : activeTab == 'OVER', hide : activeTab != 'OVER'}">
        <overview></overview>
    </div>
    <div id="about" class="{show : activeTab == 'ABOUT', hide : activeTab != 'ABOUT'}">
        <about-company></about-company>
    </div>

In the data object, set the activeTab value accordingly.

data: function () {
  return {
    activeTab: "OVER"
  }
}

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

When using Vuejs2, the list of autosize textareas connected to an expanding array of objects does not properly update their values

After binding https://github.com/jackmoore/autosize to textareas within a v-for loop, I've noticed an unexpected data persistence issue while expanding the array linked to that list: While inputs on the left side move downward as intended, new textar ...

Entering _this

I am encountering an issue with my typescript file where it is failing TSLint. I need some help resolving this problem. The structure of the object in question is as follows: export default class Container extends Vue { // methods doSomething() { ...

Navigating to a new URL using window.location.href will seamlessly embed the new page within

I am new to JavaScript and I am facing an issue with my AJAX function. The function is supposed to navigate to a new URL, but instead of loading the new page separately as if the user had typed the URL, it gets inserted inside the same div where the button ...

The art of Vue JS displaying content

Learning how to make API requests using axios has greatly improved my ability to retrieve data in a client-side container and display it in my component template. It's been quite effective so far. Having worked with twig before, I can't help ...

Mastering HTML5 Video: A guide to smoothly playing multiple videos in a loop fashion

Although similar questions have been raised in the past, none has successfully addressed this particular issue; they only provide partial solutions. The objective is as follows: We possess a collection of videos referred to as video1, video2, video3, vid ...

Exploring the functionality of JavaScript's concat method

I am trying to retrieve value1, value2, value3... but I am encountering an issue. Why am I getting this error message - "can't access property "concat", texto1 is undefined"? Please assist me! Here is the HTML code snippet: <div id=ite ...

Why should <template> be used in Vuetify?

Exploring the possibilities of Vuetify 2.0 in my current project has led me to dive into the v-stepper component, designed for displaying progress through numbered steps. In the example provided in the playground, I noticed the use of the <template> ...

Angular 2+ Service for tracking application modifications and sending them to the server

Currently I am facing a challenge in my Angular 4 project regarding the implementation of the following functionality. The Process: Users interact with the application and it undergoes changes These modifications are stored locally using loca ...

Implementing pagination within an Angular 11 Mat-table with grouping feature

Encountering an interesting issue with MatTable pagination and grouping simultaneously. I have two components each with a Mat-table featuring Pagination+Grouping. ComponentOne functions smoothly without any issues. When choosing to display 5 elements pe ...

Exploring Bootstrap4: Interactive Checkboxes and Labels

My form design relies on Bootstrap, featuring a checkbox and an associated label. I aim to change the checkbox value by clicking on it and allow the label text to be edited by clicking on the label. The issue I'm facing is that both elements trigger t ...

Associate the URL with the object to retrieve the corresponding object

https://i.sstatic.net/cj5N4.png When iterating through this array, I currently loop through it in the following manner: {props.choosenMovie.characters.map((characters) => ( <p>{characters}</p> /* This displays the URL of course */ ))} ...

Get a Blob as a PNG File

Hope you had a wonderful Christmas holiday! Just to clarify, I am new to JS and may make some unconventional attempts in trying to download my Blob in PNG format. I am facing an issue with exporting all the visual content of a DIV in either PDF or image ...

A method for applying the "active" class to the parent element when a child button is clicked, and toggling the "active" class if the button is clicked again

This code is functioning properly with just one small request I have. HTML: <div class="item" ng-repeat="cell in [0,1,2]" data-ng-class="{active:index=='{{$index}}'}"> <button data-ng-click="activate('{{$index}}')">Act ...

Issuing a straightforward GET request results in a significant delay in receiving a response

I have a simple app running on Node.js, Handlebars, and Express. The main page features a single button that triggers an asynchronous GET request when clicked, causing a console.log message to display. Initially, the first click on the Submit button shows ...

The json_encode() function returned a JSON that is not valid

In my PHP file (although more complex, even with the simplest code it fails), I have: <?php $salida = array(1,2,3,4,5); echo json_encode($salida); ?> The response received is: [1,2,3,4,5] While this appears valid, it's actually not. When pas ...

How can I assign several Objects to a single array?

My goal is to save several objects into an array. Specifically, I have five objects named obj1, obj2, obj3, obj4, and obj5. ...

Issue with creating a variable name inside a JavaScript for loop

Here is the code snippet I am currently working on: var var1 = 58; for(var i=0;i<10;i++){ if(("var"+i) == 58) { console.log("they are equal"); } } I am wondering why ("var" + i) is not equal to 58 in this scenario. Could someone please provide an ...

What is the best way to create a JavaScript Up/Down Numeric input box using jQuery?

So, I have this Numeric input box with Up/Down buttons: HTML Markup: <div class="rotatortextbox"> <asp:TextBox ID="txtrunningtimeforfirstlot" ClientIDMode="Static" runat="server">0</asp:TextBox> (In mins) </div> <div cl ...

What to do when VueJs computed method throws an error: "Cannot access property 'words' of undefined"?

Here is some pseudo code that I've written: var vm = new Vue({ el: '#test', data: { words: [{name:'1'}, {name:'2'}, {name:'3'},{name:'4'},{name:'5'},{name:'6'}], } ...

What is the most effective method in Vue to transfer data between a child component, its parent, and then the parent's parent?

When working with Vue, what is the most effective way to transfer data from a child component to its parent and then to a higher level parent? Many developers utilize emit to accomplish this task, but is emit truly the best method for passing data through ...