vue2js - how to propagate selected index with chos

2019-07-25 14:36发布

Please look at the code below. The first select box is created with chosen js. When changed it should propagate its changed value to the model to which its bound (cityid). The second normal select box is working fine and its value is propagated.

Vue.directive('chosen', {
  bind: function (el, binding, vnode, oldVnode) {

    Vue.nextTick(function() {

      $(el).chosen({
        width:'100%'
      }).change(function(){

        alert($(el).val());
        vnode.context.$emit('input', $(el).val());
        
      });
    });

  },
  update: function(el, binding, vnode, oldVnode) {

  }
});


new Vue({
  el : '#app',
  data:{
    cityid : 3,
    cities : [
      {id:1, value:'London'},
      {id:2, value:'Newyork'},
      {id:3, value:'Delhi'}
    ]
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
<script src="https://code.jquery.com/jquery-1.8.3.js"></script>
<script src="https://harvesthq.github.io/chosen/chosen.jquery.js"></script>
<link rel="stylesheet" href="https://harvesthq.github.io/chosen/chosen.css" >  
  
<div id="app">
    selected city id # {{ cityid }}
    <hr>
    <select v-chosen v-model="cityid">
      <option v-for="option in cities" :value="option.id" >{{option.value}}</option>
    </select>
    <hr>
    <select  v-model="cityid">
      <option v-for="option in cities" :value="option.id" >{{option.value}}</option>
    </select>
    
  </div>

1条回答
forever°为你锁心
2楼-- · 2019-07-25 15:15

When you are emitting in your directive, you are emitting the event from the root node (the context). You need to emit the event from the node itself. You don't have access to the $emit event, but you can examine the handlers that have been attached to the node. In this case, v-model is applying a change handler. As such, if you write your directive like this, your code should work.

Vue.directive('chosen', {
  bind: function (el, binding, vnode, oldVnode) {
    Vue.nextTick(function() {
      $(el).chosen({
        width:'100%'
      }).change(function(e){
        vnode.data.on.change(e, $(el).val())
      });
    });
  }
});

Here is an example.

查看更多
登录 后发表回答