by TekMol · 6y ago · 0 comments
I agree that templating of data is something you should use a library for. But there are great templating libraries. Handlebars for example.
Can someone give a short example of code that would be more elegant using Vue then just a simple template engine?
You could also create your own components with HBS templates and figure out how compose them to render a tree of components. That's not too hard to figure out either.
The problem is really in updating the DOM when state changes somewhere in your application. In the jQuery days we had tons of micro DOM managing code so that when some variable changed then we would update some piece of the DOM by "hand". But as your project grows this becomes a mess pretty quickly.
Another solution could be to simply re-render everything and update all the DOM on every frame with a state change. That would simplify your code but it would probably be extremely inefficient.
The point of libraries like Vue, React, Svelte, etc, is about simplifying the production of sophisticated UIs, as efficiently as possible, so you can focus on the right abstraction instead of the implementation details (eg: managing the DOM).
Every library takes a very different approach. If you're coming from the vanilla/jQuery world the learning curve can be pretty steep. But, as someone who has been doing web frontend for 20 years, I think the price of admission is worth it.
IMO Vue is probably the easiest one to get into. You can get started by simply including it in a script tag as if you were using jQuery.
Say a function changes the cars array. All it has to do to update the DOM is:
document.querySelector('#cars').innerHTML=carsTemplate(cars);
Where carsTemplate is a HandleBars template that on page load has been initialized with the html to render the list of cars.
In my experience, the approach you're describing doesn't really scale and only works for the most simplistic use cases. In a real world scenario you would have dozens if not hundreds or thousands of arrays/vars that are related to the view.
Even only considering we're talking about rendering blocks of dynamic HTML: How are you going to keep track which state changes affect which parts of the DOM? Are you going to have hundreds/thousands of innerHTML code all over the place? What is going to happen when (not if) you change your template?
Then you need to start considering, event handlers, initialization code for every car view, etc. Imagine those event handlers modify the state of a single car in your array. Are you going to repaint and re-initialize the events of all your cars on every mouse event? Again, that would probably work on very simplistic use cases.
I'm not describing anything new. These problems are what motivated people to create Ember, Backbone, Angular 1 and other frameworks some 10 years ago. But the JS world has moved on from that paradigm into the reactivity+components thing which is a much better abstraction in terms of developer experience, performance, memory consumption, etc [1].
[1] https://medium.com/dailyjs/a-realworld-comparison-of-front-e...
function update() {
let value = document.querySelector("input")?.valueAsNumber;
document.querySelector("main").innerHTML = `
Enter a price: <input type="number" oninput="update()">
<br>
Discounted price is ${value * 0.8}
`;
}
update();
What will happen is each time you enter a character, it will create a new input element, which loses the focus and cursor position.To solve this we can split it up so that the inputs are created once and the output is updated with innerHTML. No problem, right? But it's hard to scale up because now you have to split the html up into small segments based on whether there's internal state or not. If you want to update the 'max' of an input type=range, you aren't doing it with handlebars anymore but you have to use setAttribute instead.
What react, vue, etc. do for you is handle the updates in a way that reuses the existing elements. If you changed any attributes of the <input type=number>, it will not lose the focus and cursor and any other state. If you change the max of an <input type=range>, it will update the existing element (using setAttribute) without losing any other state. If you change some text, it will update the existing text node using innerText/textContent.
You may not need this type of system. I think React, Vue, etc. are overused. But in some projects it's much cleaner to use a React/Vue/etc. style system rather than splitting it up where some segments use setAttribute, some use innerHtml, etc.
What the above code will do is completely replace the HTML for the entire list of cars, when really all that needs to happen is appending one to the end. If the list is big, your app is now slow.
If the user has something focused or edited in that list of cars (let's say they're editing the description of one), not only is focus lost on that field now (its DOM node was completely wiped out and replaced), but the user's text they were editing is also lost.
Now you have to update the DOM 3x and remember that the filter you set in that one place over there means you need to only show BLUE cars in this one place over here.
When you start to build things where one piece of data is not just shown in multiple places, but is dependent on other pieces of data, managing your state starts to become more difficult than the methodology you're describing.
There are benefits to using the industry standard (which today I consider Vue, React, Angular and slowly Svelte), you can learn it quickly, as it has ton of resources and you can hire easily, as you aren't forcing someone to use some obscure, home baked js framework.
That's my take at least.
Then you are in trouble regardless of what you use :-)
A dashboard is usually for me the primary use case for one of these reactive frameworks.
I still don't get why it's okay for every other programming language to use the STL or huge dependencies, but doing so with javascript is frowned upon for some people. You wouldn't write a JSON parser yourself in CPP, you'd install something from conan or use the STL or boost for that. Why is it so bad to do the same with js?
To set one of the Minesweeper tiles to bomb, you could do:
tiles[x][y].className='bomb';
And you are done. The rendering will nicely take place according to what you defined in the CSS.
If you're building complex user interfaces or a large-scale web app, then hell yeah, you want to use React or Vue.
For reference: I recently built a really large scale website with react, including a content-management-system, custom fonts, around 50 pictures and a ton of tracking. It weighs 1,1MB total. The first request without lazy-loaded resources only uses around 200KB. Can't really argue against that.
This link might contribute to your evaluation. It's a seemingly reasonable overview of the top three frameworks. Author recommends using all three, spoiler?
- 10+ breakdowns for report - 10+ filters for report - Each filter has an include/exclude dropdown list which then has multiple features within even a single filter (so some filters are EQUALS/NOT EQUALS) others are INCLUDES/DOESNT INCLUDE/EMPTY/NOT EMPTY and all the appropriate options for each filter, not to mention clearing filters, etc - column sorting - column hiding - filtering with search - pagination on both client and server side (50K rows batching into sub pagination groups which client side takes over on server batches) - a dropdown at the top which re-initializes EVERY piece of data with a different account and changes quite literally re-initializes 50+ "states" of the UI on the page
Thinks of google analytics
First of all, we can assume doing this on the front end is 100% required. Imagine using google analytics where every single option you change is a backend request. Impossible, so now that weve gotten past that...
Imagine using something like jquery or custom JS where you try to manage the incredibly complicated input/output nature of each component of the page.
Component based design is required because you can keep all your logic for the entire app for a single TINY piece of the app in its own file. So something like a dropdown menu can get its own component called `<DropdownMenu>`, and within that you define all "outer state" that component can use as a prop, or input state (so for example, you want the items that appear in the list to be defined OUTSIDE the component so the component can be re-used). However, that component also has its own internal state, such as whether its open or not, whether its animating or not, what item is selected etc, so if a component has internal state, then you store it IN the component itself. So now the 'state' of EVERY component on the page is defined in 2 places... the originator of the state (such as the component which holds your API calls), or in the component itself. When any change takes place in ANY of those states, all components related to that state "update" automatically to use that new state. This means by simply making a new API call, the outer component state changes, and every single component that relies on that state updates accordingly, even for the most complex UI imaginable its trivial to think about 95% of the logic because all the state is exactly where you expect it to be, and when there are infinite numbers of nuanced side effects, you usually program them IN the component and you dont have to clutter your actual logic (say for instance the api updates your base state, you want the dropdown to reset to zero, so you would code this into the component itself, so that everywhere on the page that uses this component it would all follow suit).
You can have a "DropdownMenu" template, feed it the data (which you call "state") and update the according element on screen just fine.
document.querySelector('#carsDropdown').innerHTML=droppy(cars);
Where droppy is a HandleBars template that on page load has been initialized with the html that makes your fancy dropdown menu.