Putting all the parts of a component into a single file may seem odd to some programmers. After all, shouldn’t we be separating logic from templates? Shouldn’t we be separating styles from logic too?
And the answer is that the right thing to do is situation dependent, and this is something that a lot of modern programmers don’t understand. A lot of programmers seem to think that there are rules, and you must follow the rules. They don’t realize that rules should only be followed when they are helping you.
So the core question is this: is separating a single view into several files really helping your development process?
Here’s what the Vue documentation says.
One important thing to note is that separation of concerns is not equal to separation of file types. In modern UI development, we have found that instead of dividing the codebase into three huge layers that interweave with one another, it makes much more sense to divide them into loosely-coupled components and compose them. Inside a component, its template, logic and styles are inherently coupled, and collocating them actually makes the component more cohesive and maintainable.
So the argument from the Vue developers is that keeping all the code related to one view inside one file is actually more maintainable than separating them.
I tentatively agree with this.
Obviously, it’s good to separate certain things out into their own files. Foundational CSS styles and core JS helper methods should have their own place. But for all the code that makes a component unique, I think it’s easiest for developers if that is in one file.
Here are the problems I face with breaking a view into multiple files.
1. What is each file called? Where is it located?
When you separate a view into multiple files, it becomes difficult to find each file. It’s fine to have a standard for naming and locating files, but in any large software project, there are going to be situations where the standard can’t be followed for one reason or another. Maybe the view was created early in development. Maybe the view is shared. Or maybe the view was created by a trainee developer and the mis-naming was missed in the code review. Whatever the cause, file names and locations can be stumbling blocks.
At my workplace, we have hundreds of templates named
item.js.hamlbars. That’s not very helpful, but what’s more troublesome is when, for whatever reason, a list item couldn’t be named
item.js.hamlbars. In that case, I’m left searching for files with whatever code words I can guess.
2. Where is the bug?
Single File Components are a Bonus