I'm new in Vuejs and I want to change the selected tab of nav on click event I trying using function but console throw an error:
vue.runtime.global.js:8392 Uncaught TypeError: _ctx.changeTab is not a function
What I want to do, is to on @click
event run a function that change selected tab and show content depending on the selected tab in a single paragraph element
Code:
<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>
How can I achieve this? Regards
CodePudding user response:
Try like this :
<template>
<div>
<div class="hidden sm:block">
<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>
</template>
<script>
import { ref } from 'vue'
export default {
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 }
},
}
</script>