Thevananthan
Thevananthan

Reputation: 25

Vue component's (select) on-change function not called if value set from external method

I am using a Select as a Vue component and define it as a template.I am having the components data and props defined.

var MyComponent = Vue.component('my-component',{

  template: "<select v-on:change=\"onAppSelected\"	\n"+ 
  "v-model:value=\"appId\">			        \n"+
  "<option v-for=\"appChoice in appChoices\" 		\n"+
  "v-bind:value=\"appChoice.id\">{{appChoice.name}}	\n"+
  "</option>										\n"+
  "</select>",
 
  methods: {
  	onAppSelected:function(event){
    	console.log("On Change Called:", this.item.serial)
    	console.log("Event Target:",event.target.value)      
    },
  	setValue: function(selValue) {
    	this.appId = selValue;      
    },
  }, 
});

The function onAppSelected defined in the template using v-on:change is called if the option is selected from drop down manually.

But that function onAppSelected dont get triggered if the Value of the Select is set from the method setValue.

The setValue method is called from a external button.

The jquery lib .trigger("change") also dont help in this case.

jsFiddle Full Code

The link for the full implementation in the js fiddle is added for testing. check the output in console.

Can any one help me on this. Thanks in advance for reading my problem.

Upvotes: 1

Views: 3422

Answers (1)

Tang Yun
Tang Yun

Reputation: 159

from change | MDN,

change fires for <input>, <select>, and <textarea> elements when an alteration to the element's value is committed by the user. Unlike the input event, the change event is not necessarily fired for each alteration to an element's value.

This means that the change event will only be triggered if the value is "changed" by user. Also it won't fire if the user selects the same value.

You may use "watch" for detecting changes: JSFiddle

Upvotes: 3

Related Questions