index.html 2.2 KB

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