Add watchers to foo and bar and then push the new parameters to the router.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue Router - Testing</title>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>
<body>
<div id="app">
<h1>Vue Router - Query string</h1>
<hr>
<input type="text" v-model="foo">
<input type="text" v-model="bar">
</div>
<script>
const routes = [
{ path: '/' }
];
const router = new VueRouter([
routes
]);
const app = new Vue({
router,
el: '#app',
data: {
foo: 'foo',
bar: 'World',
},
watch: {
foo: {
handler: function() { this.updateUrl() },
immediate: true
},
bar: {
handler: function() { this.updateUrl() },
immediate: true
}
},
methods: {
updateUrl() {
this.$router.replace({query: {foo: this.foo, bar: this.bar}})
}
},
mounted() {
console.log('ok');
console.log(this.$router.query); // Returns me UNDEFINIED
}
});
</script>
</body>
</html>
Note: I did not test this using vue-router's browser history mode. If I'm not mistaken, that would cause a page reload on every replace. If this is the case, you can use window.history to directly manipulate the history state.