vue2js - how to propagate selected index with chosen select value in a direcitve

隐身守侯 提交于 2019-12-24 08:59:51

问题


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:


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.



来源:https://stackoverflow.com/questions/44286008/vue2js-how-to-propagate-selected-index-with-chosen-select-value-in-a-direcitve

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