Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get country code on vue tel input?

My component

<v-form>
  <v-container>
    <v-row>        
      <v-col cols="12" sm="6" md="3">
        <vue-tel-input v-model="phone"></vue-tel-input>
      </v-col>
    </v-row>
  </v-container>
  <v-btn
    color="success"
    @click="submit"
  >
    submit
  </v-btn>
</v-form>

When I click submit, I just get phone. How can I get country code too?

[Reference] https://www.npmjs.com/package/vue-tel-input-vuetify

[Codepen] https://codepen.io/positivethinking639/pen/YzzjzWK?&editable=true&editors=101

like image 825
moses toh Avatar asked Nov 10 '19 10:11

moses toh


1 Answers

It seems like vue-tel-input provides a country-changed event. According to the docs it's even fired for the first time and it returns an object:

Object {
   areaCodes: null,
   dialCode: "31",
   iso2: "NL",
   name: "Netherlands (Nederland)",
   priority: 0
}

So this event handler can be added to the component and the country code can be stored in the component as you already do for the phone value.

HTML part

<div id="app">
  <v-app id="inspire">
    <v-form>
      <v-container>
        <v-row>        
          <v-col cols="12" sm="6" md="3">
            <vue-tel-input v-model="phone" v-on:country-changed="countryChanged"></vue-tel-input>
          </v-col>
        </v-row>
      </v-container>
      <v-btn
        color="success"
        @click="submit"
      >
        submit
      </v-btn>
    </v-form>
  </v-app>
</div>

JS Part

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data() {
    return {
      phone: null,
      country: null
    }
  },
  methods: {
    countryChanged(country) {
      this.country = country.dialCode
    },
    submit() {
      console.log(this.phone);
      console.log(this.country);
    }
  }
});

Here you can see a working version: https://codepen.io/otuzel/pen/PooBoQW?editors=1011

NOTE: I don't use Vue on daily basis so I am not sure if this the best practice to modify the data via the event handler.

like image 169
Orkun Tuzel Avatar answered Nov 19 '22 15:11

Orkun Tuzel