2

Given the following:

<div id="#my-container">
    <div class="title">Companies</div>

    <div class="tab active tab-apple">Apple</div>
    <div class="tab tab-google">Google</div>
</div>
  1. When page is loaded without any tab clicks yet, whichever tab with the default active class, needs to go in the .title div. For the example above, <div class="title">Apple</div>
  2. On click of a tab, the class is switched to active, and vue.js needs to update the .title div once again.

How can this be done with vue.js? I've tried but not able to get it to work as intended.

2 Answers 2

2

The answer by David is one way to do it. But Vuejs offers in-line computations for this. So, no need to hook into any CSS event. Here's some code to explain:

Create a data property active_tab, just like David mentioned. And then bind it's value just like he's done it. In your tabs, add an click event and at that event, assign appropriate value to active_tab.

<div class="tab active tab-apple" @click="active_tab = Apple">Apple</div>
<div class="tab tab-google" @click="active_tab = Google">Google</div>

Now, to dynamically assign the active class to the respective tab, make the class attribute, a computed property, like this:

<div 
    :class="['tab', active_tab == 'Apple' ? 'active' : '', 'tab-apple']"
>
    Apple
</div>

What this code is basically doing is, :class makes class a computed property. Then the commas in the array divide the statement. So, the computation will always add tab and tab-apple classes. But, only if active_tab == 'Apple' then ? add 'active' else : add ''

Sign up to request clarification or add additional context in comments.

Comments

2

Not sure which CSS framework you are using, but normally I hook into the events thrown by the tab switching (many CSS frameworks provide this access). Once hooked into it, you can write a Vue custom directive that will take that event and use it to update a VM attribute that indicates which tab is active.

Then you can use normal mustache templating to get it into your template:

<div class="title">{{ active_tab }}</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.