美文网首页
在vue项目中使用 JSON 编辑器: vue-json-edi

在vue项目中使用 JSON 编辑器: vue-json-edi

作者: 喜欢走弯路的人 | 来源:发表于2022-09-19 16:35 被阅读0次

一、安装

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>

相关文章

网友评论

      本文标题:在vue项目中使用 JSON 编辑器: vue-json-edi

      本文链接:https://www.haomeiwen.com/subject/tprvortx.html