vue.js 2 routing in vue-material

1.4k views Asked by At

I'm currently working on a web page what uses vue.js with vue-material. I made a similar menu like this.

My goal, that one of the menu item redirect the user to an another page. I tried as a official doc says:

  <md-list-item @click="$refs.sidebar.toggle(); this.$router.push('/company');">
    <md-icon>start</md-icon> <span>Starred</span>
  </md-list-item>

But I got a vue-warn message:

[Vue warn]: Error in event handler for "click": "TypeError: this.$router is undefined"

I tried the all version: $router.push('/company');,router.push('/company');,this.router.push('/company'); but stil does not works.

On the other hand i tried to surround the md-list-item with router-link tag but it didnt work as well.

How can I define the routing inline (in the @click section)?

Thx for the responses in advance!

UPDATE:

My vue-route config in app.js:

import VueRouter from 'vue-router'
Vue.use(VueRouter)
...
const routes = [];

const router = new VueRouter({
  routes
})


const app = new Vue({
    el: '#app',
    beforeUpdate: function() {
      console.debug('app rerendering');
      console.debug(this);
    },
    beforeCreate: function() {
      console.debug('app creating');
      console.debug(this);
    },
    router,
});

But the problem is the same... If I try to call this.$router.push('/company') I got a same error: TypeError: this.$router is undefined

2

There are 2 answers

2
Evaldo Bratti On BEST ANSWER

Your router config seems ok. The problem here is this. in your @click, there is no need (you already use $refs without this :P) .

<md-list-item @click="$refs.sidebar.toggle(); $router.push('/company');">
    <md-icon>start</md-icon> 
    <span>Starred</span>
</md-list-item>

jsfiddle

1
Edmarcos Almeida On

It would be easier and cleaner as shown below::

<md-list-item to="/company">
   <md-icon>start</md-icon> 
   <span>Starred</span>
</md-list-item>