R
R
Rufix2019-11-03 01:25:51
Vue.js
Rufix, 2019-11-03 01:25:51

Select/option in Vue computed. How to use?

There is this code:

<select id="input__select">
   <option v-for="(item, index) in options" :value="item.value" :key="index" 
    @change="getMonthRate(item.value)">
            {{ item.title }}
   </option>
</select>


computed: {
    // месячная ставка (для перевода процентной ставки из годовой в месячную)
    getMonthRate (value) {
      if (value === 'year') {
        return this.percent / 12 / 100
      } else if (value === 'month') {
        return this.percent / 100
      } else {
        return 0
      }
    }
}

The bottom line is that, depending on the selected option, the function works according to a different formula.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-11-03
@Rufix

Add a property that will represent the selected select item. Instead of the getMonthRate method, make a computed property:

<select v-model="selected">
  <option v-for="item in options" :value="item.value">
    {{ item.title }}
  </option>
</select>

data: () => ({
  selected: null,
  ...
}),
computed: {
  monthRate() {
    if (this.selected === 'year') {
      return this.percent / 12 / 100;
    } else if (this.selected === 'month') {
      return this.percent / 100;
    } else {
      return 0;
    }
  },
},

UPD.
it is necessary that, depending on the selected option, the function works according to a different formula

And how different? What we have now can be greatly simplified: as value, instead of strings, there will be numbers that are directly substituted into the formula - 1/12 for year, 1 for month, 0 for the rest. Then the computed property becomes much shorter:
monthRate() {
  return this.percent * this.selected / 100;
},

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question