If you're not utilizing v-model.lazy, Vue3 Cleave js may encounter functionality issues

I am currently experimenting with cleavejs to format the thousand separator in my input numbers. I've noticed a strange behavior where if I input 1000.123, it displays as 1,000.12 which is the correct format. However, the v-model value remains as 1000.123 instead of rounding off to 1000.12. Some have suggested using v-model.lazy, but this only updates when I leave the input field.

Is there another solution to address this issue without relying on v-model.lazy?

Here is the code snippet from my current component:

<script setup lang="ts">
import { ref, watch } from 'vue'
const props = withDefaults(defineProps<Props>(), {
  type: 'text',
  required: false,
  readonly: false,
  disabled: false
})
const inputValue = ref(props.modelValue)
const emit = defineEmits<{
  (e: 'update:modelValue', value: string | number): void
}>()

watch(
  () => props.modelValue,
  () => {
    inputValue.value = numeric.format(props.modelValue)
  },
  {
    immediate: true
  }
)

watch(
  inputValue,
  () => {
    emit('update:modelValue', parseFloat(inputValue.value.toString().replace(/(\d+),(?=\d+(\D|$))/g, '$1')))
  },
  {
    immediate: true
  }
)
</script>

<template>
 <input
        class="form-input"
        v-model.lazy="inputValue"
        v-cleave="{ numeral: true, numeralThousandsGroupStyle: 'thousand' }"
        :placeholder="props.placeholder"
        :required="props.required"
        :readonly="props.readonly"
        :disabled="props.disabled"
      />
</template>

I hope to find a way for v-model to return the same value as cleavejs provides without needing to use .lazy

Answer №1

Firstly, there is no need to use the watch function here. In addition, we will not emit anything on this setter because we are waiting for the Cleavejs event.

const inputValue = computed({
  set: (text: string) => {},
  get: () => new Intl.NumberFormat('en-US').format(props.modelValue)
})

Secondly, make sure to emit raw value data from Cleavejs by listening to the onValueChanged event.

const emit = defineEmits<{
  (e: 'update:modelValue', value: number): void
}>()

const onValueChanged = (e: any) => {
  emit('update:modelValue', Number(e.target.rawValue))
}

Lastly, update your input directive accordingly.

v-cleave="{ numeral: true, numeralThousandsGroupStyle: 'thousand', onValueChanged: onValueChanged }"

For a more comprehensive example of the component, refer to the code snippet below:

<script setup lang="ts">
import { computed } from 'vue'

export interface Props {
  modelValue: number
}

const props = withDefaults(defineProps<Props>(), {})

const inputValue = computed({
  set: (text: string) => {},
  get: () => new Intl.NumberFormat('en-US').format(props.modelValue)
})

const emit = defineEmits<{
  (e: 'update:modelValue', value: number): void
}>()

const onValueChanged = (e: any) => {
  emit('update:modelValue', Number(e.target.rawValue))
}
</script>

<template>
  <input
    v-cleave="{ numeral: true, numeralThousandsGroupStyle: 'thousand', onValueChanged: onValueChanged }"
    v-model="inputValue"
  />
</template>

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

Exploring the method for obtaining parameters from a generic constructor

I have a customized class called Collection, which takes another class as a parameter named personClass. I expect the method add to accept parameters that are used in the constructor of the class User class Person { constructor(public data: object) { } ...

Identical IDs appearing in multiple buttons causing a conflict

I am currently loading content from external HTML files, specifically page1.html and page2.html. Although everything is the same except for the pictures and text, I am encountering an issue with the close button. It only closes page1.html.Feel free to chec ...

Objective subject for an element within a :not operation

I have a function that specifically excludes a style on links by targeting their IDs. Each of my links has an ID, so I use that to exclude the style. a:not([id='hopscotch_logo'] { color: red; } Now, I also want to find links that are children o ...

Why is the Bootstrap tooltip flickering and not closing on mouseout? And why are duplicate entries not being triggered?

I'm facing some issues with the code I have here: Check it out The problems are as follows: Flickering - When hovering over the images slowly, there is noticeable flickering in the tooltip box rendering 2-3 times. This seems to be related to the cla ...

Is there a way to implement personalized error management in TypeScript with Express?

For a while now, I have been using JavaScript to create my APIs but recently made the switch to TypeScript. However, I keep encountering errors along the way. One particular error handler I have set up is for when a route cannot be found, as shown below: i ...

What is the most effective method for preserving RichText (WYSIWYG output)?

I am currently using a JavaScript-based rich text editor in my application. Could you suggest the most secure method to store the generated tags? My database is MySQL, and I have concerns about the safety of using mysql_real_escape_string($text);. ...

RxJS pipe operation ignoring observable

Currently, I am in the process of transitioning an app from Promises to RxJS and I could use some guidance on whether I am heading in the right direction. Situation: I have a ModalComponent that appears when an HTTP request is sent and disappears once the ...

The use of ReactDom.render is no longer permissible in Next.js

I just set up a fresh Next JS application using Next 12. Encountering this issue consistently on every page load in the browser: Alert: The use of ReactDOM.render is no longer supported in React 18. Please switch to createRoot instead. Until you make th ...

An unexpected error occurs when attempting to invoke the arrow function of a child class within an abstract parent class in Typescript

Here is a snippet of code that I'm working on. In my child class, I need to use an arrow function called hello(). When I try calling the.greeting() in the parent class constructor, I encounter an error: index.ts:29 Uncaught TypeError: this.hello is ...

Implementing binding of JSON API responses to dropdown menus in Angular 4

In my current Angular 4 application, I am faced with the challenge of populating a dropdown menu with data from an API response. Specifically, I am struggling to retrieve the necessary information for each section from the API. The API provides data on C ...

Issue: NS_ERROR_FAILURE encountered in Firefox when using getBBox()

Is there a way to use the method getBBox() in SVG to retrieve the width and height of an element? I have included my code below, which works in Chrome but not in Firefox. If anyone has a solution to this issue, please let me know. try { console.log( ...

Converting a PHP array to a JavaScript array causes an issue of undefined variable when attempting to access a PHP array that has

I've been searching through other questions without finding the answer, so I'm reaching out for help with my specific issue. My problem is transferring a php array to a javascript array. In my code editor (phpStorm), I'm getting an error st ...

How to efficiently assign a random set of values to a group of players in Javascript/nodejs while ensuring each player does not receive their own inputted value

Within my array, I have stored the following information: players[{nickname: data.player, id: socket.id, data: playerdata}] The playerdata itself is an array playerdata[] In the first value of playerdata, each player has entered a string. (playerindex ...

Is there a way to invoke a C# method upon completion of the callback function in ScriptManager.RegisterStartupScript?

I am currently developing JavaScript methods that will be called from C# code. Once the JS methods are complete, I need to include C# code to send an email. Can anyone provide guidance on how to achieve this? ScriptManager.RegisterStartupScript(this, G ...

How can I retrieve the value of an array using ngForm in Angular 2?

One concrete example is a component I created that looks like this. @Component({ selector: 'home', template: ` <form (ngSubmit)="onSubmit(f)" #f="ngForm"> <input type="text" ngControl="people"> ...

What is the reason that modifying a textarea causes the AJAX loading of content to be interrupted?

I am currently developing a feature that allows users to quote comments on my website. When a user wants to reply to a specific comment, they can simply click on the "quote" button next to that comment. This action triggers a script that adds the quoted co ...

Verify if the username or phone number is already in use (front end)

Is there a way to verify user or phone existence on the front-end form? I'm using Yup + Formik for all my requirements, and in my backend with Sequelize, I can check if a username or phone number already exists. passport.use( 'register&apos ...

CORS issue encountered by specific user visiting the hosted website

I recently developed a bot chatting website using Django and React, which I have hosted on HOSTINGER. The backend is being hosted using VPS. However, some users are able to see the full website while others encounter CORS errors where the APIs are not func ...

Implementing Conditional Display of Span Tags in React Based on Timer Duration

In my current React project, I am facing an issue with displaying a span tag based on a boolean value. I need assistance in figuring out how to pass a value that can switch between true and false to show or hide the span tag. I tried two different methods ...

Error in scrolling previews detected in Jssor horizontal template maker

I've been working with Jssor Slider Maker and I'm using the vertical preview template that features two columns on the left side and a maximized image on the right side. After pulling the code from the developers pack, it includes scripts, CSS an ...