一、vue3中使用Json 編輯器
// 安裝
npm install vue3-json-editor --save npm install vue3-json-editor@latest --save
// 項目中使用(兩種導入方式本質(zhì)上一致,區(qū)別在于模塊的默認導出方式不同)
import { Vue3JsonEditor } from 'vue3-json-editor/dist/vue3-json-editor.cjs.js' // 使用了ES6的解構賦值語法,從CommonJS規(guī)范導出的模塊中,顯式地導入了名稱為Vue3JsonEditor的變量。這樣的話,您需要在代碼中顯式地使用該變量來創(chuàng)建組件
import Vue3JsonEditor from 'vue3-json-editor' // 直接導入了默認導出的組件,可以直接使用Vue3JsonEditor變量來創(chuàng)建組件(已經(jīng)配置了Webpack或Vite等構建工具使其能夠識別.vue文件,并通過單文件組件的方式進行開發(fā))
import { Vue3JsonEditor } from 'vue3-json-editor/dist/vue3-json-editor.cjs.js';
<Vue3JsonEditor
v-model="debugInput" // 雙向綁定數(shù)據(jù)
@json-change="jsonChange" // 改變調(diào)用事件
@json-save="onJsonSave" // 保存調(diào)用事件
@has-error="onError"
key="1"
:mode="'text'" // 默認模式tree(tree,code,form,text,view) text文本結構,比較好添加和編輯內(nèi)容.樹結構看數(shù)據(jù)比較直觀,還可以添加你想要的類型的數(shù)據(jù)
ref="editor"
:showBtns="false" // 是否展示保存按鈕
:expandedOnStart="true" // 是否展開JSON編輯器模式
v-if="form.method==2" c
lass="command-issuing-script-json"
@@blur="validate" 如果需要校驗json是否正確,可以監(jiān)測@blur事件,使用editor.validate()來校驗json數(shù)據(jù)
/>
const jsonChange = (val) => {
state.debugInput = val
state.hasJsonFlag = true
}
const onError = (err) => {
state.hasJsonFlag = false
}
// 在組件中增加 exportJson 方法
const exportJson = () => {
const data = editor.value.getJSON() // 在組件實例上獲取
const jsonDataStr = JSON.stringify(data, null, 2) // 拿到json字符串
// 注意也可以直接拿動態(tài)綁定的字段
const blob = new Blob([jsonDataStr], { type: 'application/json' })
const url = URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = 'data.json'
link.click()
URL.revokeObjectURL(url)
}
// 主要功能點
(1)支持雙向綁定:您可以使用 v-model 指令將 Vue3JsonEditor 組件與父組件中的數(shù)據(jù)進行雙向綁定。并自動格式化
二、react中使用(也可用在vue項目中)可用于java、js、json等
Monaco Editor 是一個瀏覽器端的代碼編輯器,它是 VS Code 編輯器的核心部分,可以提供強大的代碼編輯能力,它是 VSCode 的瀏覽器版本Monaco Editor 的特點包括:
(1)支持多種編程語言
(2)支持語法高亮、智能提示、自動補全等編輯器功能
(3)可以集成到 Web 應用程序中,支持在線代碼編輯
https://zhuanlan.zhihu.com/p/88828576
// 安裝
npm install monaco-editor --save
// 使用
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
// 創(chuàng)建一個編輯器容器 div,并設置其大小和位置
const editorContainer = document.createElement('div');
editorContainer.style.width = '800px';
editorContainer.style.height = '600px';
document.body.appendChild(editorContainer);
// 初始化編輯器
const editor = monaco.editor.create(editorContainer, {
value: 'console.log("Hello, world")',
language: 'javascript' // 是什么語言 'json'
readOnly: readOnly || false, // 只讀
});
// 導出(借助ioJSON包,IOJSON是一種擴展了JSON格式的數(shù)據(jù)交換協(xié)議,支持更多的數(shù)據(jù)類型并且允許通過URL引用數(shù)據(jù)以方便傳輸大量數(shù)據(jù)。iojson庫提供了一系列API來解析和序列化IOJSON格式的數(shù)據(jù),使得Javascript開發(fā)者可以方便地使用這種數(shù)據(jù)交換格式)
npm install iojson
import iojson from 'iojson';
const ioJsonData = '{"name": "Alice", "age": 25}';
const jsObject = iojson.parse(ioJsonData);
console.log(jsObject);
// Output: { name: 'Alice', age: 25 }
iojson.exportJSON(physicModel, `${physicModel.name}`) // 導出.json文件
三、瀏覽器中使用eslint: vue3+codemirror6實現(xiàn)簡易在線代碼編輯器
https://www.jb51.net/article/272037.htm文章來源:http://www.zghlxwxcb.cn/news/detail-804491.html
// 項目中使用
npm install eslint-linter-browserify --save-dev(會在package及package-lock引入)
npm i vue-codemirror
npm i codemirror // 在線編輯器
npm i @codemirror/lang-javascript
npm i @codemirror/lint
npm i @codemirror/autocomplete // 自動補全功能
npm i @codemirror/theme-one-dark // 主題
// 實現(xiàn)彈框中js腳本
import { javascript, esLint } from '@codemirror/lang-javascript'
import { linter, lintGutter } from '@codemirror/lint';
import * as eslint from 'eslint-linter-browserify'
import { basicSetup, EditorView } from 'codemirror'
import { EditorState } from "@codemirror/state";
<div class="codemirror-script" ref="scriptRef"></div>
const state = reactive({
code:
`function filter(inputData) {
var outputData=inputData
return outputData
}`,
config: {
parserOptions: {
ecmaVersion: 6,
sourceType: "module",
},
env: {
browser: true,
node: true,
},
rules: ESLINT_RULES, // 校驗規(guī)則
},
editView: {}
});
const scriptRef = ref(null)
const openDialog = (row: any) => {
state.code = `function filter(inputData) {
var outputData=inputData
return outputData
}`;
setTimeout(() => {
state.editView = new EditorView({
state: EditorState.create({
doc: state.code,
extensions: [
basicSetup,
javascript(),
lintGutter(),
linter(esLint(new eslint.Linter(), state.config))
],
}),
parent: scriptRef.value as any,
})
}, 0)
}
const onConfirm = () => {
refForm.value.validate(async (valid: boolean) => {
if (valid) {
let param = { ...form.value }
param.script = state.editView.state.doc.text.join("\n") || '' // 獲取當前編輯器的內(nèi)容字符串
// 驗證js腳本 是否包含function filter
if (!param.script.includes('function filter')) {
ElMessage.warning('js腳本必須包含filter過濾函數(shù)')
return
}
}
})
}
三、websocket連接
1、配url連接路徑:
2、代碼文章來源地址http://www.zghlxwxcb.cn/news/detail-804491.html
state.ws = new ReconnectingWebSocket({ url: state.row.sourceUrl }, (type: string, message: any) => {
let newMessage = message;
try {
newMessage = JSON.parse(message);
} catch (error) {
console.log(error);
}
state.responseJSON = newMessage;
});
// 以下是websocket類封裝
interface Props {
url: string;
reconnectInterval: number; // 重連間隔時間
heartBeatInterval: number; // 心跳間隔時間
isOpenHeartbeatMonitore: boolean; // 是否開啟心跳監(jiān)測
heartMeesage: string; // 心跳發(fā)送信息
maxReconnectAttempts: number; // 最大重連次數(shù)
}
export default class ReconnectingWebSocket {
url: string;
reconnectInterval: number;
heartBeatInterval: number;
ws: any;
heartMeesage: string;
isOpenHeartbeatMonitore: boolean;
data: any;
maxReconnectAttempts: number;
private reconnectAttempts: number;
private isClosed: boolean;
private heartBeatTimer: any;
callback: Function;
constructor(
{ url, reconnectInterval, heartBeatInterval, heartMeesage, isOpenHeartbeatMonitore = true, maxReconnectAttempts = 3 }: Props,
callback: Function
) {
this.url = url;
this.reconnectInterval = reconnectInterval || 1000; // 重連間隔時間
this.heartBeatInterval = heartBeatInterval || 30000; // 心跳間隔時間
this.ws = null;
this.isClosed = false;
this.heartBeatTimer = null;
this.heartMeesage = heartMeesage;
this.isOpenHeartbeatMonitore = isOpenHeartbeatMonitore;
this.maxReconnectAttempts = maxReconnectAttempts;
this.reconnectAttempts = 0;
this.connect();
this.callback = callback;
}
connect() {
if (this.ws) {
this.ws.close();
this.ws = null;
}
this.ws = new WebSocket(this.url);
this.ws.onopen = () => {
this.isOpenHeartbeatMonitore && this.startHeartBeat();
this.callback('open', 'WebSocket連接成功');
};
this.ws.onmessage = (event: { data: string }) => {
this.callback('message', event.data);
this.data = event.data;
};
this.ws.onclose = () => {
// 正常和異常關閉
this.data = null;
this.stopHeartBeat();
if (!this.isClosed) {
// 異常關閉 重連
if (this.reconnectAttempts < this.maxReconnectAttempts) {
setTimeout(() => {
this.reconnectAttempts++;
this.callback('close', `WebSocket第${this.reconnectAttempts}次重連`);
this.connect();
}, this.reconnectInterval);
} else {
this.callback('close', `已達到最大重連次數(shù),停止重連`);
}
} else {
this.callback('close', 'WebSocket連接關閉');
}
};
}
send(data: string) {
if (this.ws.readyState === WebSocket.OPEN) {
this.ws.send(data);
}
}
startHeartBeat() {
this.heartBeatTimer = setInterval(() => {
this.send(this.heartMeesage); // 發(fā)送心跳消息
}, this.heartBeatInterval);
}
stopHeartBeat() {
this.isOpenHeartbeatMonitore && clearInterval(this.heartBeatTimer);
}
close() {
this.isClosed = true;
this.ws.close();
}
}
到了這里,關于前端使用JSON編輯器、java編輯器、瀏覽器中使用eslint的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!