index.html 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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="https://unpkg.com/jquery"></script>
  8. <script src="https://unpkg.com/select2@4.0.3"></script>
  9. <link href="https://unpkg.com/select2@4.0.3/dist/css/select2.min.css" rel="stylesheet">
  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. <!-- using string template here to work around HTML <option> placement restriction -->
  23. <script type="text/x-template" id="demo-template">
  24. <div>
  25. <p>Selected: {{ selected }}</p>
  26. <select2 :options="options" v-model="selected">
  27. <option disabled value="0">Select one</option>
  28. </select2>
  29. </div>
  30. </script>
  31. <script type="text/x-template" id="select2-template">
  32. <select>
  33. <slot></slot>
  34. </select>
  35. </script>
  36. <script>
  37. Vue.component('select2', {
  38. props: ['options', 'value'],
  39. template: '#select2-template',
  40. mounted: function () {
  41. var vm = this
  42. $(this.$el)
  43. .val(this.value)
  44. // init select2
  45. .select2({ data: this.options })
  46. // emit event on change.
  47. .on('change', function () {
  48. vm.$emit('input', this.value)
  49. })
  50. },
  51. watch: {
  52. value: function (value) {
  53. // update value
  54. $(this.$el).select2('val', value)
  55. },
  56. options: function (options) {
  57. // update options
  58. $(this.$el).select2({ data: options })
  59. }
  60. },
  61. destroyed: function () {
  62. $(this.$el).off().select2('destroy')
  63. }
  64. })
  65. var vm = new Vue({
  66. el: '#el',
  67. template: '#demo-template',
  68. data: {
  69. selected: 0,
  70. options: [
  71. { id: 1, text: 'Hello' },
  72. { id: 2, text: 'World' }
  73. ]
  74. }
  75. })
  76. </script>
  77. </body>
  78. </html>