Pass range input value on change in Vue 2

11,383

Instead of using prop create a new data variable for slider and pass this variable in the emit, like this:

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

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

Also in App.vue you will have to listed to this emitted event like this:

<template>
    <div>
        <Slider :foo="store.foo" @change-foo="changeFoo"></Slider>
    </div>
</template>
Share:
11,383
GluePear
Author by

GluePear

PHP, MySQL, JavaScript. Laravel, Symfony, Vue, React.

Updated on June 04, 2022

Comments

  • GluePear
    GluePear almost 2 years

    In Vue 2: I have an App component, which has a 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>
    

    The problem is that the value of the slider is not being passed in the emit statement in Slider.vue. I can see why - but I'm not sure how to fix it. I tried doing:

    v-model="foo"
    

    in the input element, but Vue gives a warning that I'm not allowed to mutate props.

  • diegocl02
    diegocl02 over 2 years
    Hi, and where is the props "foo" used here? what if I want to set the default value of the slider from the parent?