codemirror.vue 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <template>
  2. <div class="vue-codemirror-wrap">
  3. <textarea></textarea>
  4. </div>
  5. </template>
  6. <script>
  7. var CodeMirror = require('codemirror/lib/codemirror.js')
  8. require('codemirror/lib/codemirror.css')
  9. export default {
  10. props: {
  11. value: {
  12. type: String,
  13. default: ''
  14. },
  15. options: {
  16. type: Object,
  17. default: function () {
  18. return {
  19. mode: 'text/javascript',
  20. lineNumbers: true,
  21. lineWrapping: true
  22. }
  23. }
  24. },
  25. },
  26. data: function () {
  27. return {
  28. skipNextChangeEvent: false
  29. }
  30. },
  31. ready: function () {
  32. var _this = this
  33. this.editor = CodeMirror.fromTextArea(this.$el.querySelector('textarea'), this.options)
  34. this.editor.setValue(this.value)
  35. this.editor.on('change', function(cm) {
  36. if (_this.skipNextChangeEvent) {
  37. _this.skipNextChangeEvent = false
  38. return
  39. }
  40. _this.value = cm.getValue()
  41. if (!!_this.$emit) {
  42. _this.$emit('change', cm.getValue())
  43. }
  44. })
  45. },
  46. mounted: function () {
  47. var _this = this
  48. this.editor = CodeMirror.fromTextArea(this.$el.querySelector('textarea'), this.options)
  49. this.editor.setValue(this.value)
  50. this.editor.on('change', function(cm) {
  51. if (_this.skipNextChangeEvent) {
  52. _this.skipNextChangeEvent = false
  53. return
  54. }
  55. if (!!_this.$emit) {
  56. _this.$emit('change', cm.getValue())
  57. _this.$emit('input', cm.getValue())
  58. }
  59. })
  60. },
  61. watch: {
  62. 'value': function (newVal, oldVal) {
  63. var editorValue = this.editor.getValue()
  64. if (newVal !== editorValue) {
  65. this.skipNextChangeEvent = true
  66. var scrollInfo = this.editor.getScrollInfo()
  67. this.editor.setValue(newVal)
  68. this.editor.scrollTo(scrollInfo.left, scrollInfo.top)
  69. }
  70. },
  71. 'options': function (newOptions, oldVal) {
  72. if (typeof newOptions === 'object') {
  73. for (var optionName in newOptions) {
  74. if (newOptions.hasOwnProperty(optionName)) {
  75. this.editor.setOption(optionName, newOptions[optionName])
  76. }
  77. }
  78. }
  79. }
  80. },
  81. beforeDestroy: function () {
  82. if (this.editor) {
  83. this.editor.toTextArea()
  84. }
  85. }
  86. }
  87. </script>
  88. <style>
  89. .CodeMirror-code {
  90. font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
  91. }
  92. </style>