Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use vue-router without a component in vue 2?

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!

like image 568
Jinjinov Avatar asked Dec 06 '17 15:12

Jinjinov


Video Answer


2 Answers

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!

like image 121
Jinjinov Avatar answered Sep 25 '22 00:09

Jinjinov


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.

like image 38
Jon Duelfer Avatar answered Sep 27 '22 00:09

Jon Duelfer