vue-router example for queries

Example showing how to keep up to date with query values

by Eduardo San Martin Morote

HTML

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

<div id="app">
  <router-link to="/">/home</router-link>
  <query-param name="foo"></query-param>
  <query-param name="bar"></query-param>
  <pre>{{ $route.query }}</pre>
  <router-view></router-view>
</div>

Babel + JSX

const QueryParam = {
	data () {
  	return { value: '' }
  },
	props: {
  	name: String
  },
	template: `
<div>
	<label>{{ name }}
  	<input v-model="value" @input="updateQuery"/>
  </label>
</div>
`,
	methods: {
  	updateQuery ({ target }) {
    	this.$router.replace({
      	query: {
        	...this.$route.query,
        	[this.name]: target.value
        }
      })
    }
  },
  watch: {
  	'$route.query' (query) {
    	this.value = query[this.name] || ''
    }
  }
}
const Home = { template: '<div>Home</div>' }

const router = new VueRouter({
  mode: 'history',
  routes: [
    { path: '/', component: Home }
  ]
})

new Vue({
	router,
  el: '#app',
  components: {
  	QueryParam
  }
})