简体   繁体   中英

How to use <select> v-model with vuex?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM