js:使用vue-codemirror实现一个语法高亮的网页代码编辑器

@codemirror code editor component for @vuejs

译文:@vuejs的codemirror代码编辑器组件

文档

  • https://github.com/surmon-china/vue-codemirror

安装

# 依赖
pnpm install codemirror vue-codemirror --save

# 语言
pnpm install @codemirror/lang-json --save
pnpm install @codemirror/lang-html  --save
pnpm install @codemirror/lang-json  --save

# 主题
pnpm add @codemirror/theme-one-dark  --save

完整依赖 package.json

{
  "dependencies": {
    "@codemirror/lang-json": "^6.0.1",
    "@codemirror/theme-one-dark": "^6.1.2",
    "codemirror": "^6.0.1",
    "vue": "^3.3.4",
    "vue-codemirror": "^6.1.1",
  },
  "devDependencies": {
    "vite": "^3.1.0",
  }
}

封装一个自定义的编辑器

CodeEditor.vue

<template>
  <codemirror
    v-model="value_"
    :placeholder="placeholder"
    :style="editorStyle"
    :autofocus="true"
    :indent-with-tab="true"
    :tab-size="2"
    :extensions="extensions"
  />
template>

<script>
// created at 2023-06-22
import { Codemirror } from 'vue-codemirror'
import { json } from '@codemirror/lang-json'
import { oneDark } from '@codemirror/theme-one-dark'

export default {
  name: 'CodeEditor',

  props: {
    // v-model
    value: {
      type: String,
      default: '',
    },
    placeholder: {
      type: String,
      default: '',
    },
    height: {
      type: String,
      default: '200px',
    },
  },

  components: {
    Codemirror,
  },

  data() {
    return {
      // 配置
      extensions: [json(), oneDark],
    }
  },

  computed: {
    value_: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('update:value', val)
      },
    },

    editorStyle() {
      return { width: '100%', height: this.height, 'font-size': '16px' }
    },
  }
}
script>

<style lang="less">style>

引入使用

<template>
    <CodeEditor v-model="value">CodeEditor>
template>

<script>
import CodeEditor from '@/components/code-editor/CodeEditor.vue'

export default {
  name: '',

  components: {CodeEditor },

  data() {
    return {
      value: ''
  }
}
script>

<style lang="less" scoped>style>

实现效果
js:使用vue-codemirror实现一个语法高亮的网页代码编辑器_第1张图片

你可能感兴趣的:(Vue,javascript,vue.js,编辑器)