[Vuejs]-Import/Require JSON file as clone into Vue data property

1👍

You need to copy the JSON before do any mutation on the forEach statement:

const GALLERY = require('core-js/support/some-page-gallery.json');

export default {

    data(){
        retrun {
            gallery: JSON.parse(JSON.stringify(GALLERY)); 
        }
    }

    //rest of your code...
}

Check this question: How to create and clone a JSON object?

0👍

You could make a copy of gallery using Object.assign like this:

`export default {

data() {
    return {
        gallery: require('core-js/support/some-page-gallery.json'),
        galleryClone: {}
    }
},

created() {

    // Prepare the images for the gallery
    this._buildImageURLs();

},

methods: {

    /**
     * Build the image urls for the gallery.
     *
     * @return void
     */
    _buildImageURLs() {
        this.galleryClone = Object.assign({}, ...this.gallery);
        Object.entries(this.galleryClone).forEach(([key, value]) => 
        {
            Object.entries(this.galleryClone[key].images).forEach(([key, source]) => {
                this.galleryClone[key].images[key] = this.$staticAsset(`/assets/images/misc/${source}`);
            });
        });

    }

}

}`

what this is doing is passing the value of gallery to galleryClone by value and not by reference. Then you could use the galleryClone variable on your component instead of gallery whenever you need to update its contents.

Leave a comment