1

I'm having issues when trying to use vue-router programatically.

When I use <router-link> in my HTML it works no problem but as soon as I try to use this.$router.push I have no luck. Below is a minimum viable snippet.

main.js

import Vue from 'vue';

import App from './App';
import router from './router';

Vue.config.productionTip = false;

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>',
});

router index.js

import Vue from 'vue';
import Router from 'vue-router';

// Pages
import Home from '@/components/pages/Home';
import CalculatorSuite from '@/components/pages/calculator-suite/CalculatorSuite';

Vue.use(Router);

export default new Router({
  routes: [
    { path: '/', name: 'Home', component: Home },
    { path: '/calculator-suite', component: CalculatorSuite},
  ],
});

App.vue

<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'App',
};
</script>  

Home.Vue

<template>
  <div class="home-parent">
    // Works 
    <router-link to="/calculator-suite">Test</router-link>
    //Doesn't work
    <button :onClick="change">Test</button>
  </div>
</template>

<script>
export default {
  name: 'Home',
  methods: {
    change() {
      // Do stuff before changing
      this.$router.push('/calculator-suite');
    },
  },
};
</script>

What can I do to allow this to work?

1
  • Fixed it. :onClick was not working on the button. @click works. Commented Apr 26, 2018 at 5:41

2 Answers 2

3

You have a problem on the listener of "click" event. You are biding a value when you should be doing @click instead of :onClick to listen to the click event.

More info about binding: https://v2.vuejs.org/v2/guide/forms.html#Basic-Usage

More info about event handling: https://v2.vuejs.org/v2/guide/events.html

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

Comments

3

Instead of onclick you need to replace it with @click or v-on:click like as below

<button @click="change">Test</button> // shorthand 
                  or
<button v-on:click="change">Test</button>

You can also use href tag to go to desired page.like as below

<a href="/calculator-suite"><button>Test</button></a>

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.