【问题标题】:How to deduce Country Code from Dial code?如何从拨号代码中推断出国家代码?
【发布时间】:2021-01-27 08:39:28
【问题描述】:

我有一个用 Vue 制作的自定义表单,其中有一个手机号码字段,我使用 Vue Int Tel 输入包作为带有标志的国家代码下拉列表。

我从国家代码下拉列表中获得了所选输入的国家拨号代码值。我想从拨号代码值中获取国家代码。例如,如果印度是选定的国家,并且我的拨号代码值为 +91,我应该如何从该特定拨号代码值推断国家代码,即 IN?

**我可以分别获取这两个值,但我不能做的是从拨号代码中推断出国家代码。

任何帮助将不胜感激!

【问题讨论】:

    标签: javascript vue.js vue-tel-input


    【解决方案1】:

    由于vue-tel-input 内部使用libphonenumber-js - 你也可以使用它:

    <template>
      <vue-tel-input ref="tel" v-model="phone" />
    </template>
    
    import parsePhoneNumberFromString from 'libphonenumber-js';
    
    export default
    {
      data()
      {
        return {
          phone: '',
        };
      },
      methods:
      {
        getCountryCode()
        {
          // vue-tel-input does not update the model if you have a default country,
          // so we have to access its internal representation
          // To avoid accessing internal data of vue-tel-input, you can either not use
          // a default country, or provide the default country as a 2nd argument to the
          // parsing function - parsePhoneNumberFromString(this.phone, this.defaultCountry)
    
          const result = parsePhoneNumberFromString((this.$refs.tel || {})._data.phone);
          return result.country;
        }
      }
    

    不要忘记将包添加到您的项目npm install libphonenumber-js

    【讨论】:

    • 谢谢,IVO GELOV!似乎 parsePhoneNumberFromString 将采用格式化的手机号码。我禁用了自动格式化。是否可以只通过国家的拨号代码,它将转换为国家代码?或者,如果可以从 vue-tel-input 组件中获取格式化数字,那么我只会将其作为参数传递给解析函数,因为我在控制台中看到 vue-tel-input 组件的 phoneObject 中有格式化值
    • 搜索metadata.min.jsonnode_modules/libphonenumber-js中的类似内容
    【解决方案2】:

    您可以像这样使用每个国家/地区代码和数字前缀创建一个对象:

    country_codes = {
        '+91': 'IN',
        '+46': 'SE',
        ...
    }
    

    并使用它来将号码前缀“翻译”为两位数的国家/地区代码。

    country_codes['+46'] //returns 'SE'
    

    您可以在此处找到所有国家/地区代码: https://countrycode.org/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-16
      • 1970-01-01
      • 1970-01-01
      • 2017-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多