Reputation: 2683
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!
Upvotes: 17
Views: 15303
Reputation: 141
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.
Upvotes: 3
Reputation: 2683
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!
Upvotes: 9
Reputation: 16495
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 )
}
}
Upvotes: 2