vue.js - 将 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>
解决方案
您可以为此使用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>
推荐阅读
- linux - bash 提示变量在 bash 函数中不起作用
- python - 无法为串联的 Pandas 系列提供列名
- ios - 使用来自 xcframework 的图标的理想方式
- c# - 在c#中逐个字母读取文件
- python - 在使用 selenium shopify 结账时遇到问题
- typescript - Vue2 使用 apollo 将 vuex 存储数据传递给指令
- python - 遍历 Panda 的 df col 以删除 str
- sql - 如何在 SQL Teradata 的第二列中只选择有名字的客户+更多内容?
- node.js - 提供静态文件,不适用于nodejs
- android - Android @TestApi 含义