vue3 使用 codemirror 实现yaml文件的在线编辑

1. 使用情形

需要对yaml文件进行在线编辑,并且进行基础格式验证
在这里插入图片描述

2. 插件下载

vue-codemirror 在线代码编辑器插件
js-yaml 用于转换json和yaml格式
@codemirror/lang-yaml 用于在编辑器中进行yaml格式验证

npm install js-yaml vue-codemirror @codemirror/lang-yaml codemirror

3. 封装yaml编辑器组件

<template>
  <codemirror
    v-model="code"
    ref="mycodemirror"
    :autofocus="true"
    :extensions="extensions"
    :indent-with-tab="true"
    @change="handleChange"
    :tab-size="2"
  />
</template>
<script lang="ts" name="CodemirrorYaml" setup>
import { Codemirror } from 'vue-codemirror'
import { yaml } from '@codemirror/lang-yaml'
import { ref } from 'vue'

const emit = defineEmits(['update:modelValue', 'update:textVal'])
const code = ref('')
const extensions = [yaml()]
const handleChange = (e: string) => {
  code.value = e
  emit('update:modelValue', code.value)
}
</script>
<style></style>

4. 父组件使用

<CodemirrorYaml v-model="updateForm.valuesSource" />

5. js-yaml 使用

import * as yaml from 'js-yaml'
// load 实现将yaml格式string转成json
const valuesSource = yaml.load('apiGateway: 172.15.15.15\napiGatewayPort: 30084\nchart: test-rt')
// dump实现将json转成yaml格式string, {apiGateway: '172.15.15.15', apiGatewayPort: 30084, chart: 'test-rt'}
const yamlString = yaml.dump(valuesSource)

6. 备注

因为@codemirror/lang-yaml需要从github拉取,在服务器拉取npm包的时候可能会出行超时问题,可以本地下载后放到项目中

在这里插入图片描述

import { yaml } from '@/components/CodeMirror/lang-yaml'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值