Exploring Vue JS: A guide to using the onChange event to dynamically update input values

I am currently utilizing the npm package vue-range-component to adjust values via a slider, which then dynamically updates in the input field.

However, I'm encountering an issue with applying the onChange event for inputs. I need to have the ability to manually change the value in the input field, such as entering the number 70, and have that value reflected in the vue-range-component.

You can find my sandbox code here.

https://i.sstatic.net/U6gux.jpg

<template>
  <div class="app-content">
    <div>
        <input type="text" v-model="value[0]" />
        <input type="text" v-model="value[1]" />
    </div>

    <vue-range-slider
      v-model="value"
      :min="min"
      :max="max"
      :formatter="formatter"
      style="margin-top: 40px"
    ></vue-range-slider>

    <div class="multi-range-value-container">
        <p>{{ value[0] }}</p>
        <p>{{ value[1] }}</p>
    </div>
    </div>
</template>

<script>
import "vue-range-component/dist/vue-range-slider.css";
import VueRangeSlider from "vue-range-component";

export default {
  data() {
    return {
      value: [0, 100],
    };
  },

  methods: {
    onChange(event) {
      console.log(event.target.value);
    },
  },

  components: {
    VueRangeSlider,
  },
  created() {
    this.min = 0;
    this.max = 1000;
    this.formatter = (value) => `$${value}`;
  },
};
</script>

Answer №1

Vue's reactivity system has a limitation when it comes to detecting changes in arrays by directly setting the value of an item using its index.

To work around this issue, you can make use of two main methods to ensure that array modifications are reactive:

// Vue.set
Vue.set(vm.items, indexOfItem, newValue)

// Array.prototype.splice
vm.items.splice(indexOfItem, 1, newValue)

By utilizing these techniques, you can prompt the VueJS reactivity system to update accordingly.

If you wish to implement this solution in your project, consider employing a watcher on a modeled value, an @change event, or an @keyup event.

Using a watcher may be more resource intensive, so opting for the @keyup event (which triggers with each keypress rather than on blur like @change) and applying debouncing could be a more efficient approach especially if the value is used for filtering, sorting, or loading purposes.

Alternatively, instead of directly setting an individual array item like value[0] = something, you can make the entire array assignment reactive by using value = [...value, something];

Answer №2

Vue reactivity can be tricky to deal with, as seen in this issue.

To resolve the problem, avoid using the v-model shortcut and instead split it up like so:

Change this code:

<input type="text" v-model="value[0]" />

to:

<input type="text" :value="value[0]" @input="changeRange(0, $event.target.value)" />

Create a method:

methods: {
  changeRange(index, value) {
    const v = parseInt(value, 10)
    this.$set(this.value, index, v)
  }
}

Update

The above fix is necessary, but there are additional issues with the vue-range-component that prevent user keyboard input on other input elements on the same page - see this and this issue

A solution has been proposed in this pull request, although it has not been officially released yet.

You may consider exploring alternative components with similar functionality due to the delays in addressing these issues by the maintainer.

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

The most effective way to initiate an action following a popup

Here's a button that triggers the opening of a popup: <button type="button" id="btnBuscarCuenta" onClick="javascript:AbrirPopUpBusqueda('id_AyudaCuentas', 'pop_cuentas_contables.cfm','', '900px&a ...

Tips for sending an input file to an input file multiple times

As a developer, I am facing a challenge with a file input on my webpage. The client can add an image using this input, which then creates an img element through the DOM. However, I have only one file input and need to send multiple images to a file.php i ...

Improving the Efficiency of JavaScript/jQuery Code

Currently, I am delving into JavaScript and jQuery. Here is the code snippet that I am working on: $("#hrefBlur0").hover(function() { $("#imgBlur0").toggleClass("blur frame"); }); $("#hrefBlur1").hover(function() { $("#imgBlur1").toggleClass("blur fra ...

What is the process for making the default text in a text box appear grayed out?

Hey there! I have this cool idea for a text box. Basically, it starts off with default text but when you hover your mouse over it, the text disappears and you can start typing as usual: If you want to see how it looks like, you can check out this link: N ...

Utilizing HTML5 Drag and Drop feature to track the initial position of the element being dragged

Currently, I am utilizing the HTML 5 Drag and Drop API to create a sortable list with auto scroll functionality. One crucial aspect I am trying to incorporate is the ability to detect which specific part of an element was grabbed by the user. Take a look ...

Promise.all does not wait for the inner Promise.all to complete before continuing

let dataObj = [ { Id: 1, name: 'Alice', Address:[{ city: 'Paris', country: 'France' }] }, { Id: 2, name: 'Bob', Address: [{ city: 'NYC', country: &a ...

The comparison between local variables and data can result in a significant drop in performance

My current project involves VueJS and Cesium, but I'm facing a performance issue with a significant drop in frame rate. While I have identified the problem area, I am unsure of why this is happening and how to resolve it. export default { name: ...

Transform a text string into JSON format using Javascript

I need help converting a text string to JSON format using JavaScript. The text string is as follows: workingtable;AB8C;book_id;7541; I want to convert it into JSON format like this: {"workingtable":"AB8C","book_id":"7541"} Is there a specific JSON funct ...

What is the best way to update a variable in a Vuetify component

I am attempting to modify the background color of <v-progress> by utilizing the variable $progress-circular-underlay-stroke, however, the changes I make do not seem to show in the output. <template> <v-progress-circular :rotate="36 ...

Error message in Vuejs: The injection "Symbol()" could not be found

I encountered an issue while using confirmdialog in primevue. The error message I received is: [Vue warn]: injection "Symbol()" not found I am unsure of the cause of this error and how to resolve it. Any assistance would be greatly appreciated ...

The element is being offset by SVG animation that incorporates transform properties

I'm working on creating a halo effect by rotating an SVG circular element using the transform rotate function. I've been using getBox to find the center point of the element, but when the rotation occurs, the overall image is getting misaligned w ...

Having trouble generating a mock constructor for the user model

While attempting to simulate my user model in order to test my service, the nest console is throwing a TypeError. I am unsure of how to properly 'emulate' the constructor of the user model. user.service.spec.ts import { Test, TestingModule } fro ...

I am experiencing issues with the detection of mouseover events on an SVG circle

I am currently working on a d3 map with zoom functionality that displays circles representing different cities. However, I am facing an issue where the mouseover event for the circles (which shows tooltips and clicking reveals some lines) seems to only reg ...

The event bus I'm using isn't functioning properly within the axios interceptor, yet it operates smoothly in all my Vue components

Currently, I am utilizing VueJs and mitt for the eventBus. The mitt is globally loaded and functioning correctly as shown below: main.js const emitter = mitt(); const app = createApp(App) app.config.globalProperties.emitter = emitter I am able to call t ...

Creating dynamic forms using AngularJS and the ng-repeat directive

i am working with AngularJS dynamic forms . According to my userid value i generated multiple form field with same model name using ng-repeat. i am not able to get this input model values due to this ng-repeat. in this example i am using static userid data ...

Error messages are appearing during the installation of mediasoup

Attempting to install via Command Prompt on Windows 7 64-bit https://i.sstatic.net/MBLNR.png following the command npm cache --force cleanhttps://i.sstatic.net/dLvHP.png ...

Troubleshooting error in Vue project: "hasOwnProperty" property or method not supported by object in IE11

While working on a vue app with vue advanced webpack template, I didn't pay much attention to Internet Explorer compatibility. However, today when I tried running the app on IE browser, I encountered some strange errors. https://i.stack.imgur.com/1e6 ...

Having trouble using $.post in jQuery AJAX with the .click() method?

I am experiencing some issues with my ajax request. It appears that the $.post method is not functioning as expected, as no request is being sent. There is also no information showing up in Firebug. Interestingly, I can make this code work: $('.c ...

The Ajax script triggers the PHP script twice

Utilizing AJAX on my HTML page, I am able to dynamically load data from a MySQL database without reloading the page and send email notifications upon certain events. The process involves Ajax calls to script.php which then makes requests to the database an ...

Guidelines for dynamically displaying <router-link> or <a> in Vue based on whether the link is internal or external

<template> <component :is="type === 'internal' ? 'router-link' : 'a'" :to="type === 'internal' ? link : null" :href="type !== 'internal' ? link : null" > <slot /> < ...