VueJS @click with anchor tags

Viewed 41386

I have a single page application with a side navigation bar which has a set of anchor tags in a list.

I want to show which content to show in the page depending on the value of the selectedPage variable. As well as change the value of selectedPage based on the link that is clicked in the side bar.

Even when including .prevent on the click event the code below does not change the value of the variable. Is there another condition I should be using instead

MyPage.html

#Navbar for selecting content
<div id="sidebar-wrapper">
      <ul class="sidebar-nav">
        <li><a href="#" @click.prevent="selectedPage ='Foo'">Foo</a></li>
        <li><a href="#" @click.prevent="selectedPage ='Bar'">Bar</a></li>
      </ul>
</div>

#Page content
<div id="page-content-wrapper">
 <div class="main-content" id="app" v-cloak>

  <div class="container-fluid" v-if="selectedPage === 'Foo'">
   <h3 class="page-title">{{selectedPage}}</h3>
  </div>

  <div class="container-fluid" v-if="selectedPage === 'Bar'">
   <h3 class="page-title">{{selectedPage}}</h3>
  </div>
 </div>
</div>

App.js

new Vue({
  el: '#app',
  data: {
    selectedPage: 'Foo',
  }
})
2 Answers

I just had an interesting scenario where I was making the button work with keyboard only for a11y.

I did this and it worked great:

Clicking the button loads a popover via vue-popperjs, which needs to be dismissed when the menu item is clicked after. I will show the entire markup and discuss it after:

<template>
    <v-popper trigger="click" :options="{ placement: 'bottom' }" enter-active-class="shadow-lg">
        <div class="popper">
            <div class="flex flex-col text-left p-2">
                <span class="text-pink font-bold py-2 px-8">Download</span>
                <a
                    :href="defaultAction"
                    class="no-underline text-grey-darkest hover:bg-pink-lighter py-2 px-8"
                    @click="$refs.downloadButton.click()"
                >
                    CSV
                </a>
                <a
                    :href="urlsAction"
                    class="no-underline text-grey-darkest hover:bg-pink-lighter py-2 px-8"
                    @click="$refs.downloadButton.click()"
                >
                    CSV with URLs
                </a>
            </div>
        </div>

        <button
            ref="downloadButton"
            slot="reference"
            class="flex items-center justify-center text-center no-underline rounded-full w-8 h-8 text-grey-darker hover:text-pink active:text-pink-darker mr-2"
            title="Download CSV"
        >
            <i class="fas fa-download"></i>
        </button>
    </v-popper>
</template>

There are two key things going on here:

  1. Place a ref on the button

  2. Fire $ref.downloadButton.click() when the <a> tag is clicked

This will close the popover when menu items are clicked, netting you some sick UX.

Related