Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting changes to an input value - vue2

I am using a date time picker component for vue2. While it renders nicely and seem to function well with basic usage, I am not able to detect changes to the input value within the vue component. I tried adding @change to the component instance, although it never seems to fire. Any idea why this is? Note, v-model updates the value of cool successfully.

Vue Methods

 export default {
        ...           
        methods: {
          someEvent() {
            alert("SUCCESS"); //this never fires
          }

Vue Markup

                       <date-picker
                                v-model="cool"
                                lang="en"
                                type="datetime"
                                input-class="date-time-picker"
                                format="MM/DD/YYYY hh:mm A"
                                @change="someEvent()"
                                :confirm="true"
                        >
                        </date-picker>

JsFiddle: https://jsfiddle.net/aw5g3q9x/

like image 710
AnchovyLegend Avatar asked Dec 13 '25 09:12

AnchovyLegend


2 Answers

When you add an event listener to a component tag (such as @change="someEvent()"), Vue will listen for a custom event to be emitted from the component. The <date-picker> component never emits a custom change event. Looking at the documentation, it appears that it only ever emits a confirm event when the optional "OK" button is pressed.

Your best option is to set a watcher on the cool property to fire the someEvent method whenever the value of cool changes:

watch: {
  cool() {
    this.someEvent();
  }
}

For future reference, if the root element of the component was an input, you could use the .native modifier to listen for the change DOM event of that input element like so @change.native="someEvent()". However, the root element of the <date-picker> component is a div, so that wouldn't work in this case.

like image 63
thanksd Avatar answered Dec 14 '25 22:12

thanksd


I do not know the datepicker, but in your case you can use variable change watcher

Vue.use(window.DatePicker.default)

new Vue({
  el: '#app',
  data () {
  	return {
    	value: ''
    }
  },
  watch: {
      value() {
      		alert("OK");
      }
 }
})
<script src="//unpkg.com/vue/dist/vue.js"></script>
<script src="//rawgit.com/mengxiong10/vue2-datepicker/master/dist/build.js"></script>
<div id="app">
  <date-picker v-model="value" lang="en" type="datetime" format="yyyy-MM-dd hh:mm:ss a" :time-picker-options="{
                                     start: '00:00',
                                     step: '00:30',
                                     end: '23:30'
                                     }"></date-picker>
                                     
                                     {{ value }}
</div>
like image 33
Petr Štipek Avatar answered Dec 14 '25 23:12

Petr Štipek