Categories
JavaScript Vue

Add a JSON Editor in a Vuejs App

Spread the love

The vue-json-ui-editor package provides an easy way to add a JSON editor into our Vue app.

We can install it by running:

npm install vue-json-ui-editor --save

Then in App.vue, we can use it as follows:

<template>
  <div id="app">
    <json-editor ref="JsonEditor" :schema="schema" v-model="model">
      <br>
      <button @click="submit">submit</button>
      <button @click="reset" type="button">Reset</button>
    </json-editor>
  </div>
</template>

<script>
import JsonEditor from "vue-json-ui-editor";
const SCHEMA = {
  type: "object",
  title: "JSON editor",
  properties: {
    name: {
      type: "string"
    },
    email: {
      type: "string"
    }
  }
};

export default {
  name: "App",
  components: { JsonEditor },
  data: () => ({
    schema: SCHEMA,
    model: {
      name: "foo"
    }
  }),

  methods: {
    submit(_e) {
      alert(JSON.stringify(this.model));
    },
    reset() {
      this.$refs.JsonEditor.reset();
    }
  }
};
</script>

We imported the JsonEditor component and specify a schema as a JavaScript object and set the schema as the value of the schema prop.

Also, we can set the title of the editor.

The schema will displayed as the controls on the screen.

Since we have 2 properties in the schema, we’ll see 2 controls displayed.

When we click Submit, we’ll see the JSON displayed.

Leave a Reply

Your email address will not be published. Required fields are marked *