Augustin Riedinger
Augustin Riedinger

Reputation: 22270

Vue + Vuex: format input data

Inspired from several example, I'm trying to write a custom component that formats it's value with a specific method.

Here's the component:

<template>
  <input
    type="text"
    v-model="inputValue"
  />
</template>

<script type="text/javascript">
  import {formatPhoneNumber} from '~/utils/string';

  export default {
    computed: {
      inputValue: {
        get() {
          return formatPhoneNumber(this.value)
        },
        set(value) {
          this.$emit('input', formatPhoneNumber(value))
        }
      }
    },
  }
</script>

I'm using Vuex, and I call the component this way in the parent component:

<PhoneInput :value="cellPhoneNumber" class="input" @input="addCellPhoneNumber" />

  computed: {
    cellPhoneNumber() {
      return this.$store.state.identity.cellPhoneNumber;
    },
  },
  methods: {
    addCellPhoneNumber: function(phoneNumber) {
      this.$store.commit('identity/addCellPhoneNumber', phoneNumber)
    },
  }

The set part works, it goes to the store, but the data comes back to the component, cellPhoneNumber is called, but not inputValue#get.

Since it might be related to the fact that I use @input/:value in the parent component, I tried to use it also on it's child component:

<template>
  <input
    @input="formatValue"
    type="text"
    :value="formattedValue"
  />
</template>

<script type="text/javascript">
  import {formatPhoneNumber} from '~/utils/string';

  export default {
    computed: {
      formattedValue: function(){
        return formatPhoneNumber(this.value)
      },
    },
    methods: {
      formatValue(e) {
        this.$emit('input', formatPhoneNumber(e.target.value))
      }
    }
  }
</script>

Without success, the same thing happens.

Can someone tell me what's going wrong?

Upvotes: 1

Views: 155

Answers (1)

Augustin Riedinger
Augustin Riedinger

Reputation: 22270

As @ohgodwhy mentioned in the comments:

You're missing a prop definition in the component that expects this.value, so it's not reactive.

Upvotes: 1

Related Questions