LovelyAndy
LovelyAndy

Reputation: 891

How to disable a button in VueJS to avoid redundant route navigation? Conditional click events possible?

I have a Home button in the app I am working on and want to stop to the error from being thrown when someone clicks on Home when they are already there. The error I get right now is

Error in v-on handler (Promise/async): "NavigationDuplicated: Avoided redundant navigation to current location: "/"."

And presently my tag looks like this in code:

<img @click="$router.push({ path: '/' })" src="/svgs/home.svg" class="home-btn" />

Is there anyway to have a conditional statement with a click event? V-if doesn't seem to work.

Upvotes: 1

Views: 328

Answers (2)

Harshal Patil
Harshal Patil

Reputation: 21030

There are multiple ways you can do that. If you are using <button>, then you can simply disable it using the condition by checking your current route.

Since, you are using the <img /> element (As per standards, disabled attribute is not available for img tag), you will have to handle that using additional condition in the handler.

// If using named views
function clickHandler() {
  if (this.$route.name !== 'home') {
    this.$router.push({ path: '/' });
  }
}

// If not using named views
function clickHandler() {
  if (this.$route.path !== '/') {
    this.$router.push({ path: '/' });
  }
}

Use the above handler for your <img /> element as:

<img @click="clickHandler" src="/svgs/home.svg" class="home-btn" />

On a side note, from accessibility point of view, consider using button or a element and wrap your image inside it. If not that, at least add tabindex to your img tag.

Upvotes: 1

Aaron Saunders
Aaron Saunders

Reputation: 33345

you can just disable the button by checking the current path using $route

see documentation - https://router.vuejs.org/api/#the-route-object

Upvotes: 0

Related Questions