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!
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With