14
votes

I have a very simple page, just a few lines of code and I would like to use vue-router without a vue-component.

I would like to get the string "my-search-query" after the root:

www.example.com/my-search-query

and use it in my main Vue() object. Is this possible?

Thank you!

3
If that's all you want to use vue-router for, just use window.location.pathnametom_h
@tom_h how would i be notified when the path would change to "my-other-search-query"? sorry for noob questions, i am just beginning to learn vue.Jinjinov

3 Answers

8
votes

It is possible to use vue-router without a vue-component and still be notified about path changes in the main Vue() app object:

You can get the "my-search-query" string from www.example.com/#/my-search-query like this:

const router = new VueRouter({
  routes: [
    { path: '/:question' }
  ]
})

const app = new Vue({
  el: '#app',
  router,
  watch: {
    '$route.params.question': function(newVal, oldVal) {
      alert(newVal === 'my-search-query');
    }
 }
});

Thanks to @samayo for pointing me in the right direction!

3
votes

Since the router is part of your view model instance, you can create a computed function that returns the path value of the router. For example, you can do the following:

data: function() {
    router: new VueRouter()
},
computed: function() {
    routerPath: function() {
        return this.router.currentRoute.path;
    }
},
watch: function() {
    routerPath: function(val) {
        switch(val) {
            case '/':
                // @TODO: logic for home
                break;
            case '/path1':
                var query = this.router.currentRoute.query;
                // @TODO: logic form query params
                break;
        }
    }
}

With this, the router will manage the history for you, but you don't have to divide your code up into components. For example, I have a pretty small page and just wanted to put everything into the same viewModel without breaking everything up into components.

2
votes

As tom_h has said you can use window.location.pathname if you just want to get the path name. If you want to be notified when this pathname changes, then first initialize it to your data(){} object and watch it as:

data () {
  return {
    path: window.location.pathname
  }
},

watch: {
  path (newpath, oldpath) {
    alert('location path just changed from ' + newpath + ' to ' + oldpath )
  }
}