How do I make a button inside a component change the vue router path

Viewed 6315

I have buttons inside of a component. I am using vue router for vuejs 2.5 and I want to the path to simply change if I click this button. How do I make the path update whenever I click the button.

const Home = { template: '<div>Home <br> <button id="t2">Click Me</button><br><button>go back</button></div>' }
const Foo = { template: '<div>Foo<br this is a page</div>' }
const hello = {
template:'t1',
data(){
return {

}
}
}

const router = new VueRouter({
  mode: 'history',
  routes: [
    { path: '/', component: Home },
    { path: '/foo', component: Foo }
  ]
})

new Vue({
 router,
  el: '#app',
  data: {
    msg: 'Hello World'
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://npmcdn.com/vue/dist/vue.js"></script>
<script src="https://npmcdn.com/vue-router/dist/vue-router.js"></script>

<div id="app">
  <router-link to="/">/home</router-link>
  <router-link to="/foo">/foo</router-link>
  <router-view></router-view>
  
  <script type="text/x-template" id="t1">
  <button>hello</button><br> 
  </script>
</div>

2 Answers

You can simple add a click listener to the button:

 <template>
  <div id="app">
    <button @click="redirectToHome()">Go Back</button>
    <button @click="redirectToFoo()">Click ME</button>
  </div>
</template>

and implement them inside methods

<script>
export default {
  name: "#app",
  methods: {
    redirectToHome() {
      this.$router.push({ path: '/' });
    },
    redirectToFoo() {
      this.$router.push({ path: '/foo' });
    }
  }
};
</script>

For further details on programmatic navigation: https://router.vuejs.org/guide/essentials/navigation.html#programmatic-navigation

Related