简体   繁体   中英

Two-way binding with Vuex

I have a state variable in store Vuex like this:

let state = {
    order: {
        payment_method: 'Credit card',
    }
};

export default state;

Then, my template:

<select id="payment_method" class="w-full form-control form-select"
        v-model="order.payment_method">
    <option value="Credit Card">Credit Card</option>
    <option value="COD">COD</option>
</select>

When I change my select option, my state order will be updated. However, should I do that, because when I read the Vuex store principle, it said I shouldn't update the state value directly? Is that the way I am doing in the above code?

If I shouldn't do that, how will I get the value from the selection option?

Exactly you shouldn't manipulate your vuex state directly. You can use Vuex Actions , Vuex Mutations and Vuex Getters to work with the state. Also in your component you could use computed Properties to get/set Vuex State data safely.

Use a computed property

In your template you could use a computed property and specificially define get and set methods for to wrap the store logic within.

<select v-model="paymentMethod">
    <option value="Credit Card">Credit Card</option>
    <option value="COD">COD</option>
</select>

{
  computed : {
    paymentMethod : {
      get() { return this.$store.getters.orderPaymentMethod },
      set(value) { return this.$store.commit('SET_ORDER_PAYMENT_METHOD', value)
    }
}

And then use this computed property as v-model for your selection v-model="paymentMethod"

Adding Mutations and Getters to your store

export const SET_ORDER_PAYMENT_METHOD = 'SET_ORDER_PAYMENT_METHOD'
const store = new Vuex.Store({
  state: {
    order: {
      payment_method: 'Credit Card'
    }
  },
  mutations : {
    [SET_ORDER_PAYMENT_METHOD] (state, method) {
       /* optional value validation here */
       state.order.payment_method = method;
    }
  },
  getters: {
    orderPaymentMethod: state => {
      /* optional filtering or else, ... */
      return state.order.payment_method
    }
  }
})
  1. Read more about Mutations here https://vuex.vuejs.org/guide/mutations.html
  2. Read more about Getters here https://vuex.vuejs.org/guide/getters.html

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