项目中有个需求,是调试接口,需要在前端写入参
本来写的输入框,但是感觉太low了,后面做了json输入
第一步
安装引入插件
npm i bin-code-editor
import CodeEditor from 'bin-code-editor'
Vue.use(CodeEditor)
第二步
使用
// 入参
<b-code-editor
ref="editor"
v-model="form.ext"
:auto-format="true"
:smart-indent="true"
theme="idea"
:indent-unit="4"
:line-wrap="false"
:show-number="true"
/>
<el-button size="mini" type="primary" @click="handleFormat">格式化校验</el-button>
// 返回参数
<b-code-editor
ref="resopnse"
v-model="form.resopnse"
:auto-format="true"
:smart-indent="true"
readonly
theme="idea"
:indent-unit="4"
:line-wrap="false"
:show-number="true"
/>
// 判断是不是json
isValidJSON(str) {
if (typeof str === 'string') {
try {
var obj = JSON.parse(str)
if (typeof obj === 'object' && obj) {
return true
} else {
return false
}
} catch (e) {
return false
}
}
},
// 点击格式化按钮
handleFormat() {
this.$refs.editor.formatCode()
setTimeout(() => {
const v = this.$refs.editor.getValue()
console.log('获取的输入框内容的数据:', v)
if (this.isValidJSON(v)) {
console.log('JSON.parse后的数据:', JSON.parse(v))
} else {
console.log(JSON.stringify(v))
}
}, 1000)
},
调用接口并回显内容
save () {
// ...这里省去接口调用 res是接口返回的数据
this.form.resopnse = JSON.stringify(res)
this.$nextTick(() => {
this.$refs.resopnse.formatCode()
})
}
属性
theme属性可选值
idea、eclipse、duotone-light、mdn-like、xq-light、dracula、rubyblue、monokai、material、material-darker
方法