Encountering a problem with creating a reusable Vue 3 component "vue-tel-input" using Vite, Composition API, and TypeScript

I recently came across the NPM package, vue-tel-input, and decided to create a separate component for it in my project. Here's how I structured it:

components/NPMPackages/VueTelInput/Index.vue

<script setup lang="ts">
import { VueTelInput } from 'vue-tel-input';
import 'vue-tel-input/vue-tel-input.css';

defineProps(['modelValue'])
defineEmits(['update:modelValue'])
</script>
<template>
  <VueTelInput
    :value="modelValue"
    @input="$emit('update:modelValue', $event.target.value)"
  >
  </VueTelInput>
</template>

After setting up the component, I tried importing it into my App.vue file as follows:

<script setup lang="ts">
import NPMPackageVueTelInput from '@/components/NPMPackages/VueTelInput/Index.vue'

const phone = ref('');
</script>

<template>
  <NPMPackageVueTelInput v-model="phone"></NPMPackageVueTelInput>
</template>

Unfortunately, I encountered an issue where I was unable to type inside the input box and nothing was displaying on the screen.

If you're interested, here is the types-definition for this package.

The environment specifications under which I faced this problem are as follows-

Vue- 3.3.4
vite - 4.4.9
typescript - 5.1.6

Interestingly, when I directly used vue-tel-input within App.vue without creating a common component, everything worked perfectly fine.

I would greatly appreciate any assistance or insights on resolving this matter.

Answer №1

Within this line of code:

@input="value => emit('update:modelValue', value)"

An InputEvent object is returned, triggering the warning message.

I took a different approach in writing your component (not the most recommended method but it gets the job done). My apologies for the messy code.

Here is my alternative solution:

<script setup lang="ts">
import { ref, watch, onMounted } from "vue";
import { VueTelInput } from "vue-tel-input";
import "vue-tel-input/vue-tel-input.css";

// Props
const props = defineProps({
  modelValue: String,
});

// Events
const emit = defineEmits(["update:modelValue"]);

// Local State
const value = ref("");

// Watch for changes in Local State
watch(value, (val) => {
  emit("update:modelValue", val);
});

// Watch for changes in Props
watch(
  () => props.modelValue,
  (val) => {
    value.value = val;
  }
);

// Set initial value
onMounted(() => {
  value.value = props.modelValue;
});
</script>

<template>
  <VueTelInput v-model="value"> </VueTelInput>
</template>


Update

You can install the @vueuse/core package and utilize the useVModel hook.

Below is the revised code using this method:

<script setup lang="ts">
import { useVModel } from '@vueuse/core'
import { VueTelInput } from "vue-tel-input";
import "vue-tel-input/vue-tel-input.css";

const props = defineProps<{modelValue: string}>()
const emit = defineEmits(['update:modelValue'])
const data = useVModel(props, 'modelValue', emit)

</script>

<template>
  <VueTelInput v-model="data"> </VueTelInput>
</template>

For more information, refer to: useVModel - @vueuse/core

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Finding the value of a computed property and toggling the visibility of a

While I may not have expertise in vue.JS programming, I've been tasked with making some adjustments to an existing app. My current challenge involves using a computed property to control the visibility of a DIV. The issue lies in the fact that the co ...

In my VueJs project, I developed a custom button component that includes a loader feature. I initially passed the loader as a prop, but I am currently facing challenges integrating it with a method in another VueJs page

Here is an example of my component: <button class="BtnLoader btn btn-primary-contained btn-iconed btn-mobile btn-important" @click="onClick" :aria-label="label" :title="title"> <i v-if="loader" cla ...

ag-grid-angular failing to present information in a table layout

I have implemented ag-grid-angular to showcase data in a structured table format, but the information appears jumbled up in one column. The data for my ag-grid is sourced directly from the raw dataset. https://i.stack.imgur.com/sjtv5.png Below is my com ...

Vue and Vuex: importing a temporary collection of child components

In our vue/vuex application, we are using an object called myObject which contains a group of children referred to as myObject.kids. When the object is initially loaded by vuex, the .kids data is not included. Now I am looking to create a component that ...

What is the best method for iterating through an array and generating a glossary list organized by categories?

I have an array filled with definitions. How can I use Vue.js to iterate through this array and create a glossary list organized by letters? Desired Output: A Aterm: A definition of aterm B Bterm: A definition of bterm C Cterm: A definition of cterm ...

Defining the type of a React hook object in TypeScript when calling it

Within my code, I have implemented the following custom hook: const count = useDocsCount({ collectionRef: 'notifications', filter: { filterKey: 'seen', operator: '==', filterValue: false } }) ...

Issue with for loop execution within subscribe event

In my chat design, there is a list of people on the left side. When a user clicks on any person, I display their chat history on the right side. To achieve this, I need to transfer user details from one component to another using an RXJS subscribe call. Da ...

Which is the most efficient method for incorporating Vue.js into Laravel projects: Inertia.js or Laravel UI?

I'm currently knee-deep in a Laravel project and now I'm onto the Vue.js integration part. After doing some research, I've discovered that there are multiple ways to bring Vue into a Laravel project, with Inertia.js and Laravel UI being the ...

After calling the service, Angular 2 is unable to perform any actions within the subscribe method

I am struggling with what to do after authenticating my user. Once I receive the data, I want to redirect them to the appropriate page based on their role and display their name on that page. I have tried various methods, but it seems like when I try to ca ...

I am encountering issues in Vue JS when using ternary expressions alongside v-if statements

Snippet:- <template> <div id="calendars-results"> <div class="vs-con-loading__container"> <div class="vs-row flex justify-between"> <h4 class="vs-row mb-2">{{ title } ...

Preventing Duplicate Random Numbers in Vue 3 and JavaScript: A Guide

I've been working on creating a function that can iterate through an array of objects with names and IDs, randomize the array, and then return one filtered item to slots.value. The current spin function successfully loops through the randomized object ...

The absence of essential DOM types in a TypeScript project is causing issues

Recently, I've been working on setting up a web app in TypeScript but I seem to be missing some essential types that are required. Every time I compile using npm run build, it keeps throwing errors like: Error TS2304: Cannot find name 'HTMLEleme ...

Leveraging cloud functions on Firebase for maximum efficiency

Question: Do you require a backend language when using Firebase Cloud Functions, or can TypeScript alone suffice for coding tasks like creating a matchmaking system? Response: There seems to be some uncertainty on the matter even from ChatGPT himself. Is ...

Tips for organizing date columns in Bootstrap-Vue when utilizing a formatter for presentation purposes

I am working with a table containing date objects, and I have transformed them for display using the following code: { key: "date", formatter: (value, key, item) => { return moment(value).format("L"); }, sortable: true } However, this ...

Exploring async componentDidMount testing using Jest and Enzyme with React

angular:12.4.0 mocha: "8.1.2" puppeteer: 6.6.0 babel: 7.3.1 sample code: class Example extends Angular.Component<undefined,undefined>{ test:number; async componentWillMount() { this.test = 50; let jest = await import('jest&apos ...

Creating a Class in REACT

Hello fellow coding enthusiasts, I am facing a minor issue. I am relatively new to REACT and Typescript, which is why I need some assistance with the following code implementation. I require the code to be transformed into a class for reusability purposes ...

What is the best way for a Vue component to update a list in a different component that it's not directly related to?

There are two main components in my project: <filter-controls></filter-controls> <data-list></data-list> The <data-list> component contains a list of items, such as ingredients, that can be filtered based on user input. Me ...

Why do I keep being told that the property doesn't exist?

I have the following code in one file: function test<T extends {}>(arg:T):any { return arg.name } In another file, I have this code: interface IItem { name: string } console.log(test<IItem>({name:'3'})) When I try to access ...

Experiencing a problem with loading the image

export const Image = { // eslint-disable-next-line no-undef bgHome: require("../Image/bg.jpeg"), }; <img src={Image?.bgHome} loading="lazy" /> Uncaught ReferenceError: require is not defined. Encountering similar issues. Failed to load backg ...

Ways to determine whether an element is presently engaged in scrolling

Is there a way to determine if certain actions can be disabled while an element is being scrolled? The scrolling may be triggered by using the mouse wheel or mouse pad, or by calling scrollIntoView(). Can we detect if an element is currently being scroll ...