vue.js :selected doesn't triggering @change event select/option

本小妞迷上赌 提交于 2019-12-06 13:27:47

问题


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..


回答1:


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).




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!