Home > Back-end >  Vue2: Why can I not set new value when using computed property?
Vue2: Why can I not set new value when using computed property?

Time:04-06

I have a property from an API (romanizationSystem_FK) that sometimes is a null value. If there is a null value, I want to set the value of that property to -1.

I've tried to do this logic via a computed property, but for some reason if the value is null it still does not get set to -1 by the computed property. Anyone spot any errors ?

Template:

        <select
          v-model="romanizationSystem_FK"
          @change="$emit('variation-updates', formValues)"
        >
          <option value=""></option>
          <option
            v-for="option in romanizationSystemOptions"
            :key="option.code"
            :value="option.code"
          >
            {{ option.system }}
          </option>
        </select>

script:


props: {
    variation: {
      type: Object,
      default: () => ({})
    },
    romanizationSystemOptions: {
      type: Array,
      default: () => []
    },
  data() {
    return {
      formValues: {
        ...this.variation
      }
    }
  },
  computed: {
    romanizationSystem_FK: {
      get() {
        return this.formValues.romanizationSystem_FK
      },
      set(val) {
        if (val === null) {
          this.formValues.romanizationSystem_FK = -1
        } else {
          this.formValues.romanizationSystem_FK = val
        }
      }
    }

CodePudding user response:

You can use Nullish coalescing operator (??). I am just creating a very simple demo to show how it works.

new Vue({
  el: '#app',
  data: {
    formValues: {
      romanizationSystem_FK: null
    }
  },
  computed: {
    romanizationSystem_FK() {
      return this.formValues.romanizationSystem_FK ?? '-1'
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input v-model="romanizationSystem_FK"/>
</div>

  • Related