首页 > 解决方案 > 将 Vue 方法拆分为多个文件?

问题描述

目前我有一个文件,我在其中根据路由参数有条件地渲染内容。我打算有 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>

标签: vue.jswebpack

解决方案


您可以为此使用mixins(在我看来很简单)或Vuex(需要一个额外的包和更多的配置)。

mixins您可以使用在mixin 本身中不存在data但在要在其中使用 mixin 的组件中存在的属性(或任何其他属性,computed,watch等。 ) (如下面的演示所示) . 这允许 mixins 非常灵活,并且意味着您不必重组大量代码/等...

Mixin(s) 示例: [ CodePen 镜像]

/* 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>


推荐阅读