![](/img/trans.png)
[英]How to change active tab background color as selected tab without click?
[英]Change selected tab on click event
我是 Vuejs 的新手,我想在單擊事件上更改選定的導航選項卡我嘗試使用 function 但控制台拋出錯誤:
vue.runtime.global.js:8392 Uncaught TypeError: _ctx.changeTab is not a function
我想要做的是在@click
事件上運行一個 function 更改選定的選項卡並根據單個段落元素中的選定選項卡顯示內容
代碼:
<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>
我怎樣才能做到這一點? 問候
移動您的陣列以設置 function,使其與 ref 反應或反應:
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.