Search code examples
javascriptvue.jsexternal

How do I move Vue data to external file?


I'm trying to keep my Vue compontent more easy to read, and there is a massive block of data (myDataStructure) which I'd like to move to an external file:

 data() {
            return {
                myDataStructure: {..................}
            }
 }

so that I have

myDataStructure: variableName

I know I can make a global variable, but that seems messy. What is the best practice to do this? I'd prefer not to get this data from an Ajax call. I'd like Vue to compile it so that it loads together with the component.


Solution

  • I think you could use es module imports for this like this:

    data-structure.js

    export default {
      someData: false,
      otherData: [],
      moreData: ''
    };
    

    my-component.vue

    import dataStructure from './data-structure.js'
    
    export default {
      name: 'my-component',
      data() {
        return dataStructure;
      }
    };