index.html 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>Vue.js custom directive integration example (select2)</title>
  6. <script src="../../dist/vue.js"></script>
  7. <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
  8. <link href="http://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet">
  9. <script src="http://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
  10. <style>
  11. select {
  12. min-width: 300px;
  13. }
  14. </style>
  15. </head>
  16. <body>
  17. <div id="el">
  18. <p>Selected: {{selected}}</p>
  19. <select v-select="selected" options="options">
  20. <option value="0">default</option>
  21. </select>
  22. </div>
  23. <script>
  24. Vue.directive('select', {
  25. twoWay: true,
  26. bind: function () {
  27. var optionsData
  28. var optionsExpression = this._checkParam('options')
  29. if (optionsExpression) {
  30. optionsData = this.vm.$eval(optionsExpression)
  31. }
  32. var self = this
  33. $(this.el)
  34. .select2({
  35. data: optionsData
  36. })
  37. .on('change', function () {
  38. self.set(this.value)
  39. })
  40. },
  41. update: function (value) {
  42. $(this.el).val(value).trigger('change')
  43. },
  44. unbind: function () {
  45. $(this.el).off().select2('destroy')
  46. }
  47. })
  48. var vm = new Vue({
  49. el: '#el',
  50. data: {
  51. selected: 0,
  52. options: [
  53. { id: 1, text: 'hello' },
  54. { id: 2, text: 'what' }
  55. ]
  56. }
  57. })
  58. </script>
  59. </body>
  60. </html>