当前位置:Gxlcms > JavaScript > vue2.x select2 指令封装详解

vue2.x select2 指令封装详解

时间:2021-07-01 10:21:17 帮助过:3人阅读

本文介绍了vue2.x select2 指令封装,分享给大家,具体如下:

其他的就不说了,说说封装过程的问题吧

1、vue不同版本指令接受参数不一样

2、酱油君对于vue2.x双向绑定的机制不了解(有大神路过望在评论中不吝赐教)

上代码:

<!DOCTYPE html>
<html>
<head>
  <title>vue select2 封装</title>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="external nofollow" rel="stylesheet" />
  <script src="https://unpkg.com/vue/dist/vue.js"></script>
  <script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
  <style type="text/css">
    .content{
      text-align: center;
      padding:50px;
    }
    .content *{
      text-align: left;
    }
    .select{
      width: 350px;
    }
  </style>
</head>
<body>
  <div class="content" id="vue-example">
    <select class="select" v-select2='options' v-model="selectValue"></select>
    <br/>
    <span>结果:{{ selectValue }}</span>
  </div>
</body>
<script type="text/javascript">
  Vue.directive('select2', {
   inserted: function (el, binding, vnode) {
     let options = binding.value || {};
 
    $(el).select2(options).on("select2:select", (e) => {
     // v-model looks for
     // - an event named "change"
     // - a value with property path "$event.target.value"
       el.dispatchEvent(new Event('change', { target: e.target })); //说好的双向绑定,竟然不安套路
    });
   },
   update: function(el, binding, vnode) {
    $(el).trigger("change");
   }
  });
 
  var vueApp = new Vue({
   el: "#vue-example",
   data: {
    selectValue: '你还没有选值',
    options: {
      data: [
          { id: 0, text: 'enhancement' },
        { id: 1, text: 'bug' },
        { id: 2, text: 'duplicate' },
        { id: 3, text: 'invalid' },
        { id: 4, text: 'wontfix' }
      ]
    }
   }
  });
</script>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

人气教程排行