button click redirection to another page vue

Button Click Redirection to Another Page in Vue

If you're building a web application using Vue, there will come a time when you need to redirect users to another page after they click a button. There are several ways to achieve this, but here are some of the most common methods:

One of the easiest ways to redirect users to another page is by using a router-link. This is a built-in component in Vue that allows you to create links that automatically update the URL and change the view. Here's an example:


<template>
  <div>
    <router-link to="/new-page">Go to New Page</router-link>
  </div>
</template>

In this example, we're using the router-link component to create a link that will take users to a new page with the URL "/new-page". When the user clicks on the link, Vue will automatically update the URL and render the new page.

Using a Method

If you need more control over the redirect process, you can create a method that handles the redirection. Here's an example:


<template>
  <div>
    <button @click="redirectToNewPage">Go to New Page</button>
  </div>
</template>

<script>
export default {
  methods: {
    redirectToNewPage() {
      window.location.href = '/new-page';
    }
  }
}
</script>

In this example, we're using a button with an @click event that triggers a method called "redirectToNewPage". This method simply updates the current URL to "/new-page", which will cause the browser to load the new page.

Using a Router Push

If you're using Vue Router, you can also use the router.push method to navigate to a new page programmatically. Here's an example:


<template>
  <div>
    <button @click="redirectToNewPage">Go to New Page</button>
  </div>
</template>

<script>
import { mapActions } from 'vuex';

export default {
  methods: {
    redirectToNewPage() {
      this.$router.push('/new-page');
    }
  }
}
</script>

In this example, we're using the router.push method to navigate to a new page when the user clicks on the button. We're also using Vuex to map the actions we need for the redirection.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe