将Vue方法拆分为多个文件?

时间:2019-04-21 23:00:16

标签: vue.js webpack

目前,我有一个文件,其中我根据路由参数有条件地渲染东西。我打算使用9种不同的参数来呈现9种不同的信息/功能。

此刻,我仅将这些功能集之一实现到此单个文件中,并且该文件非常大,主要是由于methods部分所致。

在Vue(带有Webpack)中,最好的方法是将一个文档拆分为多个文档,而无需进行大量编辑工作即可保持功能。

这是文档的当前结构:

<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 个答案:

答案 0 :(得分:0)

为此,您可以使用mixins(我认为是简单的选择)或Vuex(需要一个额外的程序包和更多的配置)。

通过mixins,您可以使用data个属性(或任何其他属性,computedwatch等。) t存在于mixin本身中,但是 do存在在您要在其中使用mixin的组件中(如下面的演示所示)。这使mixins变得非常灵活,并且意味着您不必重组很多代码/等。

Mixin(s)示例: [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>