【问题标题】:vue.js :selected doesn't triggering @change event select/optionvue.js :selected 不会触发 @change 事件选择/选项
【发布时间】:2018-03-05 07:01:59
【问题描述】:

我有道具“猫”

props: ['cat1'],

蚂蚁这段代码

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

所以这个代码在页面加载时被调用,问题是,在加载页面选项更改但它没有触发@change事件后,因为它我无法真正跟踪在页面上选择了哪个选项加载。 我用 v-model ant 等尝试了很多版本,但它看到我只是坚持下去..

【问题讨论】:

  • 所以你想在用户选择一个选项时更改cat1?
  • 你能展示一下set_category方法吗?
  • @RichardMatsen set_category 方法目前只有 console.log('test') 用于调试我想要做什么,当页面加载此代码时,它在 prop cat1 中调用,我有部分 url在 :value="category" 我实际上有整个对象...因为 cat1 来自后端我实际上想检查它们是否彼此相等,我的意思是来自类别对象(category.url)的 url 和来自道具“cat1”。他们是......然后我想通过 set_category 方法或使用任何其他方法来绑定它......
  • 抱歉没有运气。我能看到的唯一选项是使用 v-model 将 select 绑定到 cat1,然后在 cat1 上设置一个调用 set_category 的监视。

标签: javascript select vue.js vuejs2 option


【解决方案1】:

这是一个将根据需要发出更改事件的指令

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

这样使用

<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) {
  }
}

我还没有尝试过使用 prop(只是一个局部变量),但我可以说它会在绑定变量在后台更改时发出 change 事件(与 @change 不同)。

【讨论】:

    【解决方案2】:

    Richard Matsen's answer 很棒。但是,如果您只想跟踪页面加载的价值,为什么不直接在 created(或 mounted)上调用它。

    created() {
      this.set_category();
    }
    

    这是jsfiddle:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多