问题描述
目前,我正在通过在线阅读一些教程来学习vuejs
。我发现,如果该组件有很多方法,那么该组件最终可能会出现数百行?
我只是假设,因为我是新手。
然后我想到了将方法拆分到一个文件夹中的不同文件中,这是否有意义,或者这是一个不好的做法?
例如,按照一个教程的操作,在组件文件夹中,我有EmployeeForm.vue
,这是下面的代码
<template>
<div id="employee-form">
<form @submit.prevent='handleSubmit'>
<!-- form fields -->
<label for="">Employee Name</label>
<input
v-model='employee.name'
type="text"
:class="{ 'has-error': submitting && invalidName }"
@focus="clearStatus"
@keypress="clearStatus"
/>
<label for="">Employee Email</label>
<input
v-model='employee.email'
type="text"
:class="{ 'has-error': submitting && invalidEmail }"
@focus="clearStatus"
/>
<!-- error handle -->
<p
v-if="error && submitting"
class="error-message"
>
❗Please fill out all required fields
</p>
<p
v-if="success"
class="success-message"
>
✅ Employee successfully added
</p>
<!-- submit button -->
<button>Add Employee</button>
</form>
</div>
</template>
<script>
export default {
name: "employee-form",data() {
return {
submitting: false,error: false,success: false,employee: {
name: "",email: ""
}
};
},methods: {
handleSubmit() {
this.submitting = true;
this.clearStatus();
if (this.invalidName || this.invalidEmail) {
this.error = true;
return;
}
this.$emit("add:employee",this.employee);
this.employee = {
name: "",email: ""
};
this.error = false;
this.success = true;
this.submitting = false;
},clearStatus() {
this.success = false;
this.error = false;
}
},computed: {
invalidName(){
return this.employee.name === '';
},invalidEmail(){
return this.employee.email === '';
},}
};
</script>
<style scoped>
form {
margin-bottom: 2rem;
}
[class*="-message"] {
font-weight: 500;
}
.error-message {
color: #d33c40;
}
.success-message {
color: #32a95d;
}
</style>
这最多只能达到100行,但是如果methods
将来会更晚怎么办?
我正在考虑在methods
文件夹下创建一个components
文件夹
然后在methods
文件夹中包含诸如
├── EmployeeForm.vue
└── methods
├── EmployeeFormClearStatus.js
├── EmployeeFormHandleSubmit.js
└── EmployeeForm.js
在EmployeeForm.js
内部,我只有类似的东西
import handleSubmit from './EmployeeFormHandleSubmit';
import clearStatus from './EmployeeFormClearStatus';
export default { handleSubmit,clearStatus };
然后在EmployeeForm.vue
我将其更改为
// template
<script>
import EmployeeFormMethods from './methods/EmployeeForm.js';
export default {
name: "employee-form",methods: EmployeeFormMethods,}
};
</script>
// style
这实际上是否是更好的文件夹结构?
在此先感谢您的任何建议。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)