一、安装
npm install vue-json-editor --save
或者
yarn add vue-json-editor
二、使用
vue:
<template>
<vue-json-editor
v-model="jsonContent" <!--绑定的JSON数据-->
:show-btns="true" <!--是否显示按钮-->
mode="tree" <!--模式:tree text form code等-->
lang="zh" <!--语言-->
:expandedOnStart="false" <!--初始化时,是否自动展开-->
@json-change="jsonChange" <!--json改变时,触发的事件-->
@json-save="jsonSave" <!--json保存事件-->
@has-error="hasError"/> <!--出现错误时,触发的事件-->
</template>
JS:
<script>
import vueJsonEditor from 'vue-json-editor'
import '@/styles/jsoneditor.css' // 该本地文件用于覆盖编辑器默认的样式
export default {
components: { vueJsonEditor },
data() {
return {
jsonContent: null
}
},
mounted() {
this.init()
},
methods: {
// 初始化
init() {
this.jsonContent = JSON.parse(this.value)
},
// 点击按钮进行保存
save() {
if (!this.isJSON(this.jsonStr)) return this.$message.error(`json格式错误`)
this.$message.success('json格式正确')
},
// json数据改变
jsonChange() {
console.log('json change')
},
// json数据保存
jsonSave() {
console.log('json save')
},
// 数据错误
hasError() {
console.log('has error')
},
// 判断是不是JSON
isJson(str) {
if (typeof str == 'object' && str) return true
if (typeof str == 'string') {
try {
var obj = JSON.parse(str)
if (typeof obj == 'object' && obj) return true
return false
} catch (e) {
return false
}
}
},
}
}
</script>
网友评论