I have prop "cat"
props: ['cat1'],
Ant this piece of code
<select class="form-control" @change="set_category">
<option value="" disabled>Please select category</option>
<option v-for="category in categories"
:value="category"
:selected="cat1 == category.url">{{ category.name}}
</option>
</select>
So this code is called when page its loading and the problem is, that after loading the page option changes but it doesn't triggers @change event, ant because of it i can't actually track which option was selected on page load. I tried alot versions with v-model ant etc but it sees i just stuck on it..
Here's a directive that will emit the change event as required
Vue.directive('binding-change', {
update: function (el, binding, vnode) {
const model = vnode.data.directives.find(d => d.name === 'model')
if (model) {
binding.value(model.value)
}
}
})
Use it like this
<select class="form-control" v-binding-change="set_category" v-model="cat1">
<option value="" disabled>Please select category</option>
<option v-for="(category, index) in categories"
:key="index"
:value="category"
</option>
</select>
methods: {
set_category (newValue) {
}
}
I haven't tried it with a prop (just a local variable), but I can say it emits the change event when the bound variable is changed in the background (unlike @change).
Richard Matsen's answer is great. But if you only want to track value on page load, why not just call it on created (or mounted).
created() {
this.set_category();
}
Here is a jsfiddle:
来源:https://stackoverflow.com/questions/46386061/vue-js-selected-doesnt-triggering-change-event-select-option