Send the updated value of a range input when it changes in Vue 2

Working with Vue 2, there is an interesting scenario where an App component contains a nested Slider component:

App.vue

<template>
    <div>
        <Slider :foo="store.foo"></Slider>
    </div>
</template>

<script>
    import store from './components/store.js';
    import Slider from './components/Slider.vue';

    export default {
        name: 'app',

        components: { Slider },

        data() { 
            return {
                store: store
            }
        },

        methods: {
            changeFoo(foo) {
                console.log('change!', foo);
            },
        },
    }
</script>

Slider.vue

<template>
    <div>
        <input type="range" min="1" max="100" step="1" @change="changeFoo" />
    </div>
</template>

<script>
    export default {
        props: ['foo'],
        methods: {
            changeFoo() {
                this.$emit('changeFoo', foo);
            }
        }
    }
</script>

Encountering a challenge where the value of the slider is not being properly passed in the emit statement within Slider.vue. This issue arises due to restrictions on mutating props in Vue. One attempt to resolve this involved adding:

v-model="foo"

within the input element, but Vue flagged it as an invalid operation that cannot mutate props.

Answer №1

Instead of utilizing the prop attribute, create a new data variable for the slider component and then pass this variable in the emit function as shown below:

<template>
    <div>
        <input v-model="sliderValue" type="range" min="1" max="100" step="1" @change="updateFoo" />
    </div>
</template>

<script>
    export default {
        props: ['foo'],
        data() {
           return {
              sliderValue: ""
           }
        },
        methods: {
            updateFoo() {
                this.$emit('changeFoo', this.sliderValue);
            }
        }
    }
</script>

In addition, in the App.vue file, make sure to listen to the emitted event like this:

<template>
    <div>
        <Slider :foo="store.foo" @change-foo="handleFooChange"></Slider>
    </div>
</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

Differences in how line breaks are handled in script output have been observed when comparing Atom and Notepad

Currently, I am utilizing a small script that generates a .txt file and inputs some data into it. Strangely, when I open the .txt file in Atom, the content appears on separate lines as I intended. However, when I access the same file in notepad, all the co ...

Anomaly in Express route regular expressions

I have a question that may seem silly, but I'm struggling to figure it out. I want to match any route that doesn't contain a specific word, like "api" (excluding /api/*), but I can't seem to make it work: '/^(?=\/).(?!api\/). ...

Adding a JavaScript library to your Grunt project involves a few simple steps

I've been working on an existing project built with Ionic framework. I'm trying to integrate push notifications using Ionic's feature, but when running the grunt command, I encountered the following error: Running "jsbeautifier:files" (jsbe ...

Transforming data structures into arrays using Javascript

Could someone help me with converting the following code snippet? const words = {told: 64, mistake: 11, thought: 16, bad: 17} I need it to be transformed into: const words = [ {text: 'told', value: ...

Navigating through content with scrollable views while utilizing the popular Angular framework

Being relatively new to famous and somewhat familiar with angular. Question: Given that everything in famous is fixed positioning, how should I go about creating a scrollable section using famous angular? HTML: This code snippet creates a grid of square ...

Having some trouble implementing the functionality of hiding a data series in HighCharts using `{ data: [], visible: false }` notation

I am currently working on creating a graph that displays multiple series obtained from JSON data in a MySQL database. My goal is to have the graph show only one series initially. Thankfully, HighCharts offers an option to achieve this as demonstrated below ...

Buttons failing to vanish after being clicked

Hey there! I've been working on a code snippet that displays 2 buttons based on the user's query, such as 'Yes' and 'No'. The idea is that once a button is clicked, both buttons should vanish. To achieve this functionality, I ...

Puppeteer tutorial: Scraping links from HTML elements with custom class names

There are multiple divs with the class "xj7". Directly beneath them, lies a link specified by an "a href" tag. I'm trying to figure out how to access the value within this link. The challenge is there are numerous elements sharing the same classname ...

Properties of objects changing dynamically

<div id="bach">Bach</div> <div id="show">about composer</div> $(window).load(function(){ bach = {"bdate": 1685, "bplace": "Eisenach, Germany"} $("div").click(function(){ $("#show").text(this.id['bdate']); // ...

Unable to retrieve HTML content through a Node.js server

I created a HTML webpage that includes .css, images and JavaScript files. However, when I start my node server using the command below: app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); }); The webp ...

Issue with Angular2 Router not recognizing route for homepage

I recently incorporated the Angular2 Webpack Starter into my Angular2 app, which has been working great. However, after adding a fallback route to my app.routes.ts file and including its module (NotFoundModule) in app.module.ts, I encountered an issue wher ...

What is the correct way to configure environment variables in a Next.js application deployed on Vercel?

As I develop my web app in Next.js, I have been conducting tests to ensure its functionality. Currently, my process involves pushing the code to GitHub and deploying the project on Vercel. Incorporating Google APIs dependencies required me to obtain a Cli ...

Utilizing client-side validation in ASP.NET MVC with C# for optimal performance

My client-side validation using jQuery successfully validates empty spaces in my @EditorFor() controls. However, the error persists even after filtering data. In addition, I am seeking examples to improve my logic so that when an error occurs, it is displ ...

Automatically send a form with Ajax when the page is loaded

I have a form that needs to be automatically submitted when the page loads. Here is my current jQuery code: <script> // wait for the DOM to be loaded $(document).ready(function() { document.getElementById('form1').submit( ...

Preventing Vimeo from continuing to play when the modal is closed by clicking outside of it

I am facing an issue with my Vimeo video embedded in a modal. The video stops playing when I click on the 'close' button, but it continues to play in the background when I click off the modal. I have tried solutions from similar questions without ...

Accessing data in form rules with Vuetify: tips and tricks

Is it possible to access a data element within a rule? Click here to see my code in action I'm attempting to change the value of a data element on a text field rule within a Vuetify form. While the rule itself is functioning properly, I'm enco ...

The Ionic tab is already finished displaying even before the data has completed loading

Creating a favorites section for a vouchers app has proven to be slightly challenging. When attempting to retrieve the current user's favorite vouchers and display them using ngFor in the HTML, I encountered an issue. The very first time I open the fa ...

What could be causing the response data from an AJAX request to be in error instead of success?

My JSON data is securely stored on , and I can access it through a unique URL. Here is the specific URL: The JSON data found at the above URL is: { "glossary": { "title": "Suyog", "GlossDiv": { ...

Executing two nested loops with a delay in jQuery

I am currently working on a script that sends an ajax post to another page. I need to run two for loops before sending the ajax request with a timeout. The first loop is successful, but when I try to run the second loop, all requests are sent at the same ...

Having trouble with Vue3 ref not updating?

Can someone help me understand how refs work? I feel like I'm missing a simple mistake, but it's just not clicking for me. Could someone please explain? I have props passed from the outer component in the script setup: const props = defineProps( ...