Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

vue.js - Vue - change default input text value dynamically

I have a simple Vue form component, it has some text inputs:

<input type="text" class="form-control" v-model="amount">

This text input has the following default value:

mounted() {
    this.$store.commit('refreshBalance')
  },

  data() {
      return {
        amount: this.$store.getters.baseBalance,
      };
  },

The problem with my code is that the value of amount is always the same, it doesn't change if i change the value of that Vuex store.

So, for example, if when i open the page this.$store.getters.baseBalance is equal to 10 and i change it to 20, the default value of that input field will always be 10. Is there any way i can make it reactive? Thanks in advance.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Change it to a computed property, and use the get and set methods. You’d also need to create an action in your store to update the baseBalance, which in the code below I’ve named SET_BALANCE.

When you update the input, the set method runs, which commits the value of amount to the store via. SET_BALANCE.

<input type="text" class="form-control" v-model="amount">

...

computed: {
  amount: {
    set(amount) {
      this.$store.commit('SET_BALANCE', { amount })
    },
    get() {
      return this.$store.getters.baseBalance
    }
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...