Currently i have a file in which i am rendering stuff conditionally based on route params. I intend to have 9 different params that render 9 different sets of information/features.

At the moment i have only implemented one of these sets of features into this singular file, and the file is very large, mostly due to the methods sections.

In Vue (with webpack), what is the best way to split one document into multiple documents without having to do a tonne of edit work to keep the functionality.

This is the current structure of the document:

<template>
  <div class='container' v-if="id=='exampleparam'"></div>
  <!-- This is repeated 9 times, with forms etc. inside each div for functionality -->
</template>
exports default {
    data () {
        return {
           //data stuff
        }
    },
    methods: {
        //methods for feature 1

        //methods for feature 2

        //etc.....
    },

    created () {
        //Authentication stuff that i want to stay in this file

        switch(this.id){
            case 'exampleparam':
                this.getAllExampleParamData() //function to get information for this feature from database
                break

            //Repeat cases for each feature
        }
    }
}
//Styles for the page
<styles></styles>

1 Answers

0
Matt Oestreich On

You could use mixins (easy option, in my opinion) or Vuex (requires an extra package and a little more config) for this..

With mixins you can use data properties (or any other property, computed, watch, etc..) that don't exist within the mixin itself, but do exist in the component in which you want to use the mixin in (as demonstrated in the demo below). This allows mixins to be very flexible, and means you don't have to restructure a lot of code/etc...

Mixin(s) Example: [CodePen mirror]

/* FIRST FEATURE MIXIN */
const firstFeatureMixin = {
  methods: {
    // pretend there are more methods here
    firstFeatureFirstMethod() {
      this.fromFirstFeature = "I am from feature 1 mixin";
    }
  }
};

/* SECOND FEATURE MIXIN */
const secondFeatureMixin = {
  methods: {
    // pretend there are more methods here
    secondFeatureFirstMethod() {
      this.fromSecondFeature = "I am from feature 2 mixin";
    }
  }
};

/* MAIN VUE APP */
new Vue({
  el: "#app",
  mixins: [firstFeatureMixin, secondFeatureMixin],
  data: {
    fromFirstFeature: "",
    fromSecondFeature: ""
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>

<div id="app">
  <div>
    <div>
      <div>
        <button @click="firstFeatureFirstMethod">Load from first feature file</button>
      </div>
      <div>
        {{ fromFirstFeature }}
      </div>
    </div>
    <div style="margin-top: 20px;">
      <div>
        <button @click="secondFeatureFirstMethod">Load from second feature file</button>
      </div>
      <div>
        {{ fromSecondFeature }}
      </div>
    </div>
  </div>
</div>