1

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?

3
  • 1
    You're missing a prop definition in the component that expectsthis.value, so it's not reactive. Commented Dec 9, 2019 at 17:46
  • Great! Thanks I thought props were optional, simply adding constraints or warnings instead of having a real behavioral impact. Commented Dec 10, 2019 at 8:59
  • 1
    I do wish that aspect of Vue was a bit more intuitive, or at least gave more information than what it does. Commented Dec 10, 2019 at 9:15

1 Answer 1

1

As @ohgodwhy mentioned in the comments:

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.