The number input component that is meant to be reusable is experiencing functionality issues within the NUXT framework

I have a reusable input component that is being used in various places.

Everything works well with the number input, but the issue arises when I completely clear the input. This action triggers a warning message in the console:

[Vue warn]: Invalid prop: type check failed for prop "value". Expected Number with value 0, got String with value "".

found in

---> <Numberinput> at components/utilities/numberinput.vue
       <Createproplayout> at components/layout/createproplayout.vue
         <Pages/property/create.vue> at pages/property/create.vue
           <Nuxt>
             <Layouts/form.vue> at layouts/form.vue
               <Root>

My code snippet is shown below:

Here is my reusable input component:

<template>
    <div class="normal-form">
        <!-- number input -->
        <input  
            type="number"
            :name="name" 
            :placeholder="placeholder" 
            :value="value" 
            @input="$emit('input', $event.target.value) ">
    </div>
</template>

<script>
export default {
    props: {
        name: {
            type: String,
            required: true
        },
        placeholder: {
            type: String,
            required: false,
            default: "text goes here"
        },
        value: {
            type: Number,
        }
    }
}
</script>

Usage example:

<numberinput placeholder="xxx" name="price" v-model.number="form.price.amount">Amount </numberinput>

data() {
    return {
        form: {
            price: {
                currency: 'NGN',
                amount: null,
            }
        },        
    }
},

https://i.sstatic.net/5C7o4.png Here is how it appears after entering a number and then clearing the input field.

Answer №1

The v-model.number modifier should be applied directly to the

<input type="number"
. In this case, the input will initially return a string.

  1. To convert the string from the input into a number, you can utilize the parseFloat function.
<input  
   type="number"
   :name="name" 
   :placeholder="placeholder" 
   :value="value" 
   @input="$emit('input', parseFloat($event.target.value))">
  1. An alternative approach is to create a functional component (compatible with Vue 2) that inherits attributes, props, and listeners from the input. This way, your component mimics a native
    <input type="number">
    while adding a default "type" and a wrapping div.
export default {
   name: 'number-input',
   functional: true,
   render(h, context) {
     const inputNumber = h('input', {
        ...context.data, // Inherit all HTML attributes and listeners
        props: context.props, // Inherit all props
        type: 'number',
     })
    
     return h('div', {
        staticClass: 'normal-form',
     }, [
       inputNumber
     ])
   }
}
<number-input v-model.number="form.price.amount" placeholder="xxx" name="price" />

<!-- Will compile down to -->
<div class="normal-form">
   <input type="number" v-model.number="form.price.amount" placeholder="xxx" name="price">
</div>

Answer №2

Even though @Kapcash made an attempt to address the issue, I still encountered NAN showing up in the console. To resolve this issue, I implemented a watcher on the form.price.amount field. This watcher checks if the value is of type string and converts it to null if it is.

Here is the updated code snippet:

    watch: {
        "form.price.amount": function (val) {
            if (typeof val === 'string') {
                this.form.price.amount=null
            }
        }
    },

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

Modify the click function from <tr> to <td> tag

I want to create an HTML page that functions as a digital library for books. Users should be able to click on a rate button to save the selected book to local storage, allowing them to see their rating whenever they revisit the page. However, I'm enc ...

What is the process for deselecting text from a text field?

After performing a search and displaying the results on my search form, I've noticed that the text query in the textfield is being marked as selected text even though I don't want it to be. How can I prevent this? Fiddle 1) What is the best app ...

What is the functionality of ng-repeat in AngularJS when used outside the "jump" table?

Currently, I am in the process of constructing a layout using a table with nested ng-repeat. <div ng-controller="PresetManageController"> <table> <in-preset ng-repeat="preset in presetManage.presets"></in-preset> </table ...

What is the best way to simulate a library in jest?

Currently, I am attempting to simulate the file-type library within a jest test scenario. Within my javascript document, this particular library is utilized in the subsequent manner: import * as fileType from 'file-type'; .... const uploadedFil ...

What is the process of exporting ES6 from main.js in Vue.js 2.0?

I've encountered an issue while using the webpack-simple-2.0 template for Vue.js (version 2.0.0-beta.5). When I include export const FOO='bar' in my main.js file, I'm unable to successfully import { FOO } in another .js file - it alway ...

Having trouble setting up Nuxt with Typescript integration

I am venturing into the world of Typescript with Nuxt (version 2.6.1) for the first time. After creating a new project using create-nuxt-app, I followed the official guide for Typescript Support. npx create-nuxt-app my-first-app cd my-first-app npm instal ...

Obtaining data from a CSV file and transforming it into JSON format results in an array

Currently, I am working on a function that takes a JSON object and prints it out as strings: GetAllArticles: (req, res) => { var allArticles = getAllArticles(); res.setHeader("Content-Type", 'application/json'); res.w ...

Experiencing Limitations with Node.JS node-hbase Scan Functionality, Unable to Retrieve More than 1000

I am facing an issue while trying to retrieve records from an HBase table in Node.JS using the node-hbase module, which connects to the rest server. I am able to fetch the first batch of records successfully, but I am struggling to get the next set of re ...

The distinct behavior of 'this' when using arrow functions in VueJs

Let's delve into 3 different scenarios that are puzzling me. Arrow functions typically have lexical scoping, but there are cases where the behavior seems inconsistent to me. I'm looking for some clarification on these specific situations. 1. Ins ...

JavaScript treats string as a primitive value

When it comes to JavaScript, a String is considered a primitive value. However, it can also be treated as a String object. In programming terms, a primitive value refers to a value assigned directly to a variable. This raises the question: var d = "foo"; ...

Locate a specific data point within an array of JSON objects

After receiving an array of JSON objects from JSP, I now have a set of data that contains book titles. "Titles":[ { "Book3" : "BULLETIN 3" } , { "Book1" : "BULLETIN 1" } , { "Book2" : "B ...

Could someone teach me how to implement icon rotation in Vue.js using Vuetify?

I am currently working on adding a feature where the icon rotates when the button is clicked, moving from down to up and vice versa in a spinning motion. Here is the code I have so far: <template> <v-btn v-on:click="isShow = !isShow" ...

Failure in rendering components with React and ElectronThe issue of rendering components with

As a newbie to the world of React and Electron, I have been experimenting with separating my components into different JSX files and importing them to render in div tags within my index page for an Electron app. However, I'm facing some confusion as i ...

Reacting with Angulatory: Response heads are not being transferred in applications

I'm facing an issue where the cookie containing my authentication token doesn't get passed along with my requests. After authenticating in Chrome, the response sets the cookie correctly, but it's not included in subsequent requests. This is ...

Assign the "this" keyword of App.vue to the Vuex state

I have discovered a workaround for accessing vue-router and other services that only works within a Vue component. By saving the "this" of the Vue app in the state of Vuex within the created option of App.vue. Is this a good approach or could it potential ...

Having difficulty in dynamically loading an image from an API's URL in Angular

In the title, I mentioned that I am utilizing a free API to display cryptocurrency news for my practice project. Everything seems to be working fine except for displaying the images in card view. I will share my code here, so if you have any suggestions on ...

How can I retrieve a Vuex data property from another Vuex data property?

In order to make color variables easily accessible throughout my Vue app, I have stored them in an array named "colors[]" within the Vuex store. This method works well when accessing the colors within component methods or inline styles. Now, I am storing ...

A function cannot be used with Random Song Loop

Recently delving into the world of JavaScript, I encountered a peculiar issue. When attempting to execute the following code within a function, nothing displays in the console. Yet, after testing it without the function, the expected strings appear as inte ...

Modify the paragraph's class upon clicking the radio button

I have been struggling with changing the color of <p> based on the radio button selected using two classes, red and blue. However, for some reason, it's not working as expected. If anyone has any insights or suggestions on how to fix this issue ...

Sort an array by mapping it in decreasing order based on the total sum of its elements

I came across a JSON structure that looks like the following: { "user": [ {"username": "x1", "pfp": "", "scores": [{"easy": 10, "normal": 1, "hard": 2, "oni&q ...