index.html 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. $(this.$el).select2({ data: options })
  55. }
  56. },
  57. destroyed: function () {
  58. $(this.$el).off().select2('destroy')
  59. }
  60. })
  61. // mock an event because the v-model binding expects
  62. // event.target.value
  63. function mockEvent (value) {
  64. return {
  65. target: {
  66. value: value
  67. }
  68. }
  69. }
  70. var vm = new Vue({
  71. el: '#el',
  72. template: '#demo-template',
  73. data: {
  74. selected: 0,
  75. options: [
  76. { id: 1, text: 'Hello' },
  77. { id: 2, text: 'World' }
  78. ]
  79. }
  80. })
  81. </script>
  82. </body>
  83. </html>