Switch to the designated tab when clicked

I'm new to Vuejs and I am struggling to change the selected tab in the navigation bar when clicking on it. I tried using a function but I keep getting an error message in the console:

vue.runtime.global.js:8392 Uncaught TypeError: _ctx.changeTab is not a function

CodePen

What I'm attempting to do is, on the @click event, run a function that changes the selected tab and displays content based on the selected tab within a single paragraph element.

Here is the code snippet:

<template>
  <div>
    <div class="sm:hidden">
      <label for="tabs" class="sr-only">Select a tab</label>
      <select id="tabs" name="tabs" class="block w-full focus:ring-indigo-500 focus:border-indigo-500 border-gray-300 rounded-md">
        <option v-for="tab in tabs" :key="tab.name" :selected="tab.current">{{ tab.name }}</option>
      </select>
    </div>
    <div class="hidden sm:block">
     <nav class="flex space-x-4" aria-label="Tabs" :class="bg-gray-600">
        <a v-for="tab in tabs" @click="changeTab(tab)"  :key="tab.name" :href="tab.href" :class="[tab.current ? 'bg-purple-700 text-white' : 'text-purple-700 hover:text-gray-700', 'px-12 py-2 font-medium text-sm rounded-full font-bold text-lg']">
          {{ tab.name }}
        </a>
      </nav>
    </div>
  </div>
</template>

<script>
const tabs = [
  { id: 1 , name: 'LOREM', href: '#test1', current: false },
  { id: 2, name: 'IPSUM', href: '#test2', current: false },
  { id: 3, name: 'PDF', href: '#test3', current: true },
]
export default {
  setup() {
    return {
      tabs,
    }
    
     function changeTab(selectedTab){
      let test = this.tabs.find(selectedTab.id);
       
       console.log(test)
    }
  },
}
</script>


<style>
  nav {
    width: max-content; 
    display: flex;
    gap: 20px; 
    background: #E5E5E5; 
    border-radius: 20px; 
}
</style>

Any suggestions on how to successfully achieve this? Thank you

Answer №1

You should consider moving your array to the setup function and making it reactive using ref or reactive:

const { ref } = Vue
const app = Vue.createApp({
  setup() {
    const tabs = ref([
      { id: 1 , name: 'LOREM', href: '#test1', current: false },
      { id: 2, name: 'IPSUM', href: '#test2', current: false },
      { id: 3, name: 'PDF', href: '#test3', current: true },
    ])

    const changeTab = (selectedTab) => {
      tabs.value.map(t => {
        t.id === selectedTab.id ? t.current = true : t.current = false
      });
    }

    return { tabs, changeTab }

  },
})
app.mount('#demo')
nav {
    width: max-content; 
    display: flex;
    gap: 20px; 
    background: #E5E5E5; 
    border-radius: 20px; 
}
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/1.0.5/tailwind.min.css">
<div id="demo">
  <div>
    <div class="">
     <nav class="flex space-x-4 bg-gray-600" aria-label="Tabs" >
        <a v-for="tab in tabs" @click="changeTab(tab)"  :key="tab.name" :href="tab.href" :class="[tab.current ? 'bg-purple-700 text-white' : 'text-purple-700 hover:text-gray-700', 'px-12 py-2 font-medium text-sm rounded-full font-bold text-lg']" >
          {{ tab.name }}
        </a>
      </nav>
    </div>
    <div v-for="tab in tabs" @click="changeTab(tab)"  :key="tab.name" :href="tab.href" class="px-12" :class="[tab.current || 'hidden']">
      {{ tab.id }} - {{ tab.name }} - {{  tab.href }}
    </div>
  </div>
</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

Creating TypeScript Classes - Defining a Collection of Objects as a Class Property

I'm trying to figure out the best approach for declaring an array of objects as a property in TypeScript when defining a class. I need this for a form that will contain an unspecified number of checkboxes in an Angular Template-Driven form. Should I ...

Why is receiving input value in React not successful?

Attempted to retrieve input value when user clicks search, but encountered difficulties. var Login = React.createClass({ getInitialState: function () { return {name: ''}; }, handleSearch(){ alert(this.state.name); // Why isn't ...

Transcribing live content directly from the browser tab

I have a unique idea for developing a browser extension specifically for Chrome. This extension would provide live transcriptions of my team's meetings directly from an open tab in the browser. I am interested in extracting keywords, such as my name, ...

Difficulty arises when Jest tests struggle to interpret basic HTML tags within a React Component

When running test runs, issues arise when using standard HTML tags with Jest. My setup includes Babel, Webpack, Jest, and React Testing Library. To enable jest, I have installed a number of packages: "@babel/plugin-proposal-class-properties": "7.8.3", "@ ...

The header location functionality is not functioning properly on the live server

I have a single registration and payment page where the program flow goes from registration to confirmation and then to payment. Upon validation and calculation on the registration page, it should redirect to the confirmation page. This is my code: < ...

What is the best way to access a reference to the xgrid component in @material-ui?

Is there a way to obtain a global reference to the xgrid component in order to interact with it from other parts of the page? The current code snippet only returns a reference tied to the html div tag it is used in, and does not allow access to the compo ...

Exploring Keypress events with Dojo's 'on' module

Recently, I've started utilizing Dojo's latest on module for event handling. It has been working well so far, but a new issue has cropped up. Specifically, when using the keypress event, I am unable to retrieve the character value (such as "2" or ...

What is the best method for simultaneously listening to several events?

For instance, I am interested in setting up a situation where a callback is triggered only when ALL specified events occur: on(['aEvent', 'bEvent', 'cEvent'], callback) The callback function should receive an array (or objec ...

Steps for submitting a form through an ajax callback

After delving into the world of Ajax, I encountered a problem that has me stumped. Initially, I am requesting data to populate a table, but I'm unsure how to tackle the issue. load_data(); function load_data(page) { $.ajax({ ...

Generating JSON Data with the Power of JavaScript and JQuery

Looking to dynamically generate a JSON Object with the specified structure: { "deleteId":[1,2,3], "pointId":[1,2,3], "update":[ { "what":"mission", "id":1, "value":"adsda" }, { ...

A guide on changing state in React Native

Currently, I am in the process of developing a lightweight project with React Native, and I have come across some challenges that I am finding difficult to overcome. :( On one of the pages in my project, I have included a pair of buttons - one labeled Yes ...

Having trouble getting SVG animations to work properly when using the static folder in Parcel?

As I was attempting to display my SVG file on the browser after uploading it to my domain, I followed a similar process to other projects where I had installed parcel. This involved creating a static folder and placing the SVG file inside it. While the SVG ...

Define a universal URL within JavaScript for use across the program

When working with an ASP.NET MVC application, we often find ourselves calling web service and web API methods from JavaScript files. However, a common issue that arises is the need to update the url in multiple .js files whenever it changes. Is there a me ...

The functionality of Vue Router Keep-Alive Inclusion is not functioning properly

I am encountering an issue with my Vue Router setup. Here is how it looks: export default new Router({ routes: [ { path: '/', name: 'Inbox', component: Inbox }] }) In the main app.vue file, I have the follo ...

Heroku-hosted application experiencing issues with loading website content

I have been working on a nodejs application that serves a web page using express and also functions as a discord bot. The app runs smoothly on localhost with both the web page and discord functionalities working correctly. However, when I deploy it to Hero ...

"Discover the magic of jQuery: Unveiling the hidden div with one simple CSS visibility change

I want to implement a functionality on my screen where the Previous button is hidden initially and only becomes visible when the user clicks the Next button. I have set the CSS property for the Previous button to hide it by default, but despite using an if ...

Adding JavaScript in the code behind page of an ASP.NET application using C#

Currently, my challenge involves inserting a javascript code into the code behind page of an asp.net application using c#. While browsing through various resources, I stumbled upon some solutions provided by this website. Despite implementing them as inst ...

Vue JS ensures that it has all the necessary data before proceeding with the

I've been grappling with a VueJS data rendering issue for a few weeks now. My approach involves making axios calls, some nested within others. The problem I'm facing is that the data renders before the calls have completed, resulting in an empty ...

Update nbind using `NODE_MODULE_VERSION 70` rather than `NODE_MODULE_VERSION 48`

I am currently working on a project using Electron. The main file where my application is launched is ./src/index.js: const { app, BrowserWindow, ipcMain } = require('electron'); const nbind = require('nbind'); const lib = nbind.init() ...

Using NodeJS to store the value from a callback function in a variable external to the function

I am facing a situation where I need to assign the value inside a callback function to a variable outside of it. Below is an example using child_process. callback.js let result; require('child_process').spawn('python', ['./hello.py ...