JSONEditor, Vue and Vuex

Posted: 2018-08-20 17:36:30

As I post here I wanted to use JSONEditor as a component. But with Vuex I was able to reduce the work quite a ton. Here is my store for the json_field:

export default {
    state: {
        json_field: null,
    },
    getters: {
        json_field: state => {
            return state.json_field;
        }
    },
    mutations: {
        jsonField(state, json_field) {
            state.json_field = json_field;
        }
    },
};

Then my JSONEditor.vue component:

<template>
    <div id="jsoneditor" ref="editor"></div>
</template>

<script>
    import JSONEditor from 'jsoneditor';
    import { mapGetters } from 'vuex'

    export default Vue.extend({
        computed: {
            ...mapGetters(
            { json_field: 'json_field' }
            ),
        },
        mounted() {
            let container = this.$refs.editor;
            let options = {
                onChange: () => {
                    this.$store.commit("jsonField", editor.get());
                },
                modes: ["tree", "text"],
            };
            let editor = (container) ? new JSONEditor(container, options) : null;
            if(container) {
                editor.set(this.json_field);
            }
        }
    });
</script>

<style type="text/css">
    #jsoneditor {
        width: 1000px;
        height: 600px;
    }
</style>


Finally the component that will use it:

<template>
    <section>
        <b-form-group id="metrics"
            label="Metrics"
            label-for="metrics"
            description="Paste as it should be">
            <cat-json-editor v-if="show_editor"></cat-json-editor>
        </b-form-group>
    </section>
</template>

<script>
import JSONEditor from 'jsoneditor';

export default {
    data() {
        return {
            form: {},
            show_editor: false
        }
    },
    created() {
        this.getStandardMetrics();
    },
    methods: {
        getStandardMetrics() {
            axios.get('/api/standards').then(res => {
                this.$snotify.success("Loading Standards", "Success");
                this.$store.commit("jsonField", res.data);
                this.show_editor = true;
            }).catch(err => {
                this.$snotify.warning("error getting metric standars", "Error");
            })
        }
    }

}
</script>

If do the v-if to load the editor AFTER I have some state for it. I am sure I could have done some watcher but this worked.


Tags:

vuejs laravel