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>
Comments
-
GluePear almost 2 years
In Vue 2: I have an
App
component, which has aSlider
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 inSlider.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 over 2 yearsHi, and where is the props "foo" used here? what if I want to set the default value of the slider from the parent?