index.html 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. </div>
  19. <script type="text/x-tempalte" id="demo-template">
  20. <div>
  21. <p>Selected: {{ selected }}</p>
  22. <select2 :options="options" v-model="selected">
  23. <option disabled value="0">Select one</option>
  24. </select2>
  25. </div>
  26. </script>
  27. <script type="text/x-template" id="select2-template">
  28. <select>
  29. <slot></slot>
  30. </select>
  31. </script>
  32. <script>
  33. Vue.component('select2', {
  34. props: ['options', 'value'],
  35. template: '#select2-template',
  36. ready: function () {
  37. var vm = this
  38. $(this.$el)
  39. .val(this.value)
  40. // init select2
  41. .select2({ data: this.options })
  42. // emit event on change.
  43. .on('change', function () {
  44. vm.$emit('input', mockEvent(this.value))
  45. })
  46. },
  47. watch: {
  48. value: function (value) {
  49. // update value
  50. $(this.$el).select2('val', value)
  51. },
  52. options: function (options) {
  53. // update options
  54. console.log(options)
  55. $(this.$el).select2({ data: options })
  56. }
  57. },
  58. destroyed: function () {
  59. $(this.$el).off().select2('destroy')
  60. }
  61. })
  62. // mock an event because the v-model binding expects
  63. // event.target.value
  64. function mockEvent (value) {
  65. return {
  66. target: {
  67. value: value
  68. }
  69. }
  70. }
  71. var vm = new Vue({
  72. el: '#el',
  73. template: '#demo-template',
  74. data: {
  75. selected: 0,
  76. options: [
  77. { id: 1, text: 'Hello' },
  78. { id: 2, text: 'World' }
  79. ]
  80. }
  81. })
  82. </script>
  83. </body>
  84. </html>