I have a <select>
in my template:
<select v-model="amount" required>
<option value="10">10</option>
<option value="20">20</option>
<option value="25">25</option>
<option value="30">30</option>
</select>
data () {
return {
amount: '',
}
}
Can I somehow put amount
in vuex state?
Yes, you can. First, setup your Vuex store to hold the value and the mutation:
store
state: {
amount: null
},
mutations: {
SET_AMOUNT(state, payload) {
state.amount = payload;
}
}
You need a way to call the mutation when the model changes and to update the model if the state changes. A computed setter is an elegant tool to handle both directions and avoid improperly mutating Vuex state in the component:
Create a computed
in the component:
component
computed: {
amount: {
get() { return this.$store.state.amount },
set(value) { this.$store.commit('SET_AMOUNT', value) }
}
}
This will work with the template the way it is in your post.