I was creating a reusable tabs component by watching tutorial. Having watched it, I figured out how it works. But, as for my project, I need to create tabs with heading containing a title that can be changed because this is a reusable component, so I have to change each heading's title for each new tab, but I haven't figured out how to do it. I need somehow to get title from component TabsWrapper that I added to my page
<div >{{title}}</div>
and then make this title change a text inside this div that is the main header of a TabsWrapper component.
<div >{{title}}</div>
My code: The first one is the code out of component that I added to my homepage of the website.
<TabsWrapper>
<Tab title="Tab 1">Hello 1</Tab>
<Tab title="Tab 2">Hello 2 </Tab>
<Tab title="Tab 3">Hello 3</Tab>
<Tab title="Tab 4">Hello 4</Tab>
</TabsWrapper>
The second one is the code inside the component that is responsible for TabsWrapper
<template>
<div >
<div ></div>
<ul >
<li
v-for="title in tabTitles"
:key="title"
@click="selectedTitle = title"
:
>
{{ title }}
</li>
</ul>
<slot />
</div>
</template>
<script>
import { ref} from 'vue';
import { provide } from 'vue';
export default{
setup(props,{slots}){
const tabTitles=ref(slots.default().map((tab)=> tab.props.title))
const selectedTitle=ref(tabTitles.value[0])
provide("selectedTitle", selectedTitle)
return{
selectedTitle,
tabTitles,
}
}
}
</script>
This chunk of code takes each title from Tab
<Tab title="Tab 1">Hello 1</Tab>
And this chunk of code renders it out
<li
v-for="title in tabTitles"
:key="title"
@click="selectedTitle = title"
:
>
{{ title }}
</li>
I've tried to repeat the same technique, but it worked out, but I think that there's the better way to do it
<div >
<div v-for="headtitle in headTitles" :key="headtitle">{{headtitle}}</div>
<ul >
<li
v-for="title in tabTitles"
:key="title"
@click="selectedTitle = title"
:
>
{{ title }}
</li>
</ul>
<slot />
</div>
</template>
<script>
import { ref} from 'vue';
import { provide } from 'vue';
export default{
setup(props,{slots}){
const tabTitles=ref(slots.default().map((tab)=> tab.props.title))
const headTitles=ref(slots.default().map((tab)=>tab.props.headtitle))
const selectedTitle=ref(tabTitles.value[0])
provide("selectedTitle", selectedTitle)
return{
selectedTitle,
tabTitles,
headTitles,
}
}
}
</script>
CodePudding user response:
You can simply pass props in the script tag and directly access them using this keyword and prop name.
export default {
props: ['foo'],
created() {
// props are exposed on `this`
console.log(this.foo)
}
}
In the template tag like this
<span>{{ foo }}</span>
you don't need to use ref you can directly use v-for and loop over the array elements.
<li v-for="(item, index) in foo">
{{item}}
</li>