index.html 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. params: ['options'],
  27. bind: function () {
  28. var self = this
  29. $(this.el)
  30. .select2({
  31. data: this.params.options
  32. })
  33. .on('change', function () {
  34. self.set(this.value)
  35. })
  36. },
  37. update: function (value) {
  38. $(this.el).val(value).trigger('change')
  39. },
  40. unbind: function () {
  41. $(this.el).off().select2('destroy')
  42. }
  43. })
  44. var vm = new Vue({
  45. el: '#el',
  46. data: {
  47. selected: 0,
  48. options: [
  49. { id: 1, text: 'hello' },
  50. { id: 2, text: 'what' }
  51. ]
  52. }
  53. })
  54. </script>
  55. </body>
  56. </html>