javascript - vue自定义指令,全局和局部css效果不同
伊谢尔伦
伊谢尔伦 2017-04-11 12:54:52
0
1
859

1.问题

想用codemirror做实时代码高亮,自定义了双向指令来使用它。定义为全局指令后可正常使用,定义为局部指令则css不正确(也许是js也有问题?)

2.代码

使用vue-cli的webpack模版建项目。codemirror通过npm安装。代码:

main.js

import Vue from 'vue'
import App from './App'

import CodeMirror from 'codemirror/lib/codemirror'
import 'codemirror/lib/codemirror.css'
import 'codemirror/mode/javascript/javascript'

Vue.directive('banzi', {
  twoWay: true,
  bind: function () {
    this.codemirror = CodeMirror(this.el, {
      mode: 'javascript',
      lineNumbers: true
    })
    this.codemirror.on('change', function () {
      this.set(this.codemirror.getValue())
    }.bind(this))
  },
  update: function (value, oldValue) {
    this.codemirror.setValue(value || '')
  }
})

/* eslint-disable no-new */
new Vue({
  el: 'body',
  data: {
    'neirong': 'function test() {}'
  },
  components: { App }
})

index.html

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8"/>
</head>

<body>
  
  <h1>from app</h1>
  <app></app> 
  
  <h1>from banzi</h1>
  <p v-banzi="neirong"></p>

</html>

components/App.vue

<template>  
  <!--<textarea id="myTextArea2" cols="10" rows="10" v-snippet="msg" v-model="msg"></textarea>-->
  <p id="app" v-snippet="msg"></p>
</template>

<script>
import CodeMirror from 'codemirror/lib/codemirror'
import 'codemirror/lib/codemirror.css'
import 'codemirror/mode/javascript/javascript'
export default {
  data () {
    return {
      msg: ''
    }
  },
  directives: {
    'snippet': {
      twoWay: true,
      bind: function () {
        this.editor = CodeMirror(this.vm.$el, {
          lineNumbers: true,
          mode: 'javascript'
        })
        this.handler = function () {
          this.set(this.editor.getValue(), true)
        }.bind(this)
        this.editor.on('change', this.handler)
      },
      update: function (value, oldValue) {
        this.editor.setValue(value || '')
        console.log(this.editor.getMode())
      }
    }
  }
}
</script>

3.截图

上面app那个是来自组件App.vue的结果,行号显示和代码冲突了,有overlap

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(1)
小葫芦

看这里吧,有人写了一个:

https://github.com/chenjiangsong/vue-codemirror
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template