How to bind radio buttons to a vuex store?
The default html <input>
component and most of the 3rd party component libraries rely on two-way binding and totally ignore vuex. All sample code suggests using the v-model
attribute. Combined with vuex this leads to problems. Vuex will complain:
Do not mutate vuex store state outside mutation handlers
So we have set up one-way binding, while keeping the proper radio button behaviour.
<template>
<input type="radio" name="info-source"
value="1" :checked="infoSource === 1"
@change="updateInfoSource(1)">
...
</template>
<script>
...
computed(): {
infoSource() {
return this.$store.state.infoSource
}
}
</script>
This snippet does the following:
- set the
checked
state based on the value of the computed fieldinfoSource
- update the store in the
@change
event