Vue, Angular, React
Front-end In today’s world of increasing complexity, there are three frameworks we are familiar with. Vue, React and Angular are often discussed and compared, such as learn which?
The core problem solved by the front-end framework
When I got started, Vue was the first thing I learned, which basically skipped background PHP, JSP and JQuery, and the three frameworks became one of the three development problems. In the later work and study, I gradually realized that the core problem solved by the front frame lies in data and view synchronization, and I also found that many people have realized this. And the core problem needs to be solved in the front end of popularization to the public
How does the front-end framework solve the complex mapping of data to views
We say is the core issue of the front-end data and the view of synchronization, here I can use a personal feel is more suitable for nouns, the mapping of the data to the view, so the framework is based on the thinking of how to think about it, we here to a discussion of functions, the first is the JQuery implementation, we need to update the input box value
Direct imperative
// The value of the current username
let curUsername = 'cj'
// Find the element with the class name username
let username = $('.username')
// Set username to cj
username.val(curUsername)
Copy the code
Follow these steps to complete our small requirements
-
Define the modified value
-
Find the elements that need to be modified
-
Change the value of the element to the value we gave it
The problem
Finding the element and setting its value is clearly imperative, and if we need to do more than one operation, an easy way to do this is to repeat the code multiple times
Using functions for maintenance
function updateUsername(username) {
let usernameInput = $('.username')
usernameInput.val(username)
}
let curUsername = 'cj'
updateUsername(curUsername)
Copy the code
From the above code, it can be abstracted that we only need to care about the changed value and the changed element, and other details we do not need to know. The process of selecting and modifying elements in the middle can be considered to be completely separated into a new abstraction. The following is the thinking based on this
Deeper thinking
Since our concern is that the target element, data, both of which can be determined at compile time, as long as we update the data, the system will update the corresponding reference this data element, to amend the us from the specified elements, elements of repeated labor, this is a basic train of thought, of course the Vue USES is the train of thought, React takes the violent diff approach
The current implementation
-
Vue binds the data to the node and updates the corresponding element when the data is updated
-
React is relatively straightforward. It diff the entire component directly to find out the difference before and after. There is no need to know the corresponding relationship between data and nodes internally
-
Angular, with little contact, currently seems to be a combination of dirty checking and proxy
Problems solved by Virtual DOM
At present, Virtual DOM and the accompanying DIff algorithm are gradually appearing in front of everyone. Why do we introduce these two sets of technologies here? React was introduced in response to slow DOM updates, cross-platform updates, etc
Why the Virtual DOM
Virtual DOM was introduced when React was launched. Personally, the React system does not know which nodes correspond to the data, so it must update all nodes according to the conventional way. React needs a set of solutions for performance optimization before operating nodes. This is how React introduced Virtual DOM technology
Why did Vue introduce Virtual DOM
Many current Vue responsive basic implementations look like this:
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial - scale = 1.0 "> < / head > < body > < div id = 'app' > < h3 > name < / h3 > < p > {{name}} < / p > < h3 > age < / h3 > < p > {{age}} < / p > < / div > < / body > < HTML > < script > document. The addEventListener (' DOMContentLoaded ', function () {let opt = {el: '# app, data: {name:' retrieval... ', age:30}} let vm = new Vue(opt) setTimeout(() => {opt.data.name = 'wang Yinfeng'}, 2000); }, false) class Vue{ constructor(opt){ this.opt = opt this.observe(opt.data) let root = document.querySelector(opt.el) Observe (data){object.keys (data). ForEach (key => {let obv = new Observer() data["_"+key] = data[key] // Use getter setter to expose for loop scope obV, DefineProperty (data, key, {get(){observer.target && obv.addSubNode(observer.target); Return data['_'+key]}, set(newVal){obv.update(newVal) data['_'+key] = newVal}})})} Compile (node){[].foreach. call(node.childNodes, child =>{if(! child.firstElementChild && /\{\{(.*)\}\}/.test(child.innerHTML)){ let key = RegExp.$1.trim() child.innerHTML = child.innerHTML.replace(new RegExp('\\{\\{\\s*'+ key +'\\s*\\}\\}', 'gm'),this.opt.data[key]) Observer.target = child this.opt.data[key] Observer.target = null } else if (child.firstelementChild) this.compile(child)}) constructor(){this.subnode = []} addSubNode(node){ this.subNode.push(node) } update(newVal){ this.subNode.forEach(node=>{ node.innerHTML = newVal }) } } </script>Copy the code
Simplifies the code is the core of Vue1 implementation, each data know reference node precision, the realization of the Vue is compiled on each node, the reference data for its generated a Watcher, obviously, for each reference data node to generate a Watcher, there is a larger memory pressure, how to solve, very simple, Push the granularity to the component level and hand the low-granularity DIff to the Virtual DOM
Front-end framework cognitive reflection
The core of the framework solution is the selection of nodes, the operation of nodes in the process of abstraction, hidden in the framework implementation, we only need to pay attention to the relationship between data and nodes, the rest of the technology is optimized in this context.
Data-driven solution
Data-driven solutions determine the performance and subsequent performance and optimization direction. Data-driven is a big trend in the front end and has become a must-have feature of the framework, because from the previous discussion, operating nodes, modifying nodes can be well abstracted and optimized. Here is a brief discussion of data-driven solutions for the three frameworks
Vue
Data-driven design
Vue2 data driven or hijacked and Virtual DOM solution, that maintain a relatively accurate update ability and keep the low level of memory usage, Vue this way has a natural performance advantages, so everyone on the cognition of component not only want to know the component reuse is extracted, in fact, the components can be a good code components, Maintaining the right size of components also allows for a natural performance optimization with Vue2’s data-driven solution, which I’ll look at later on in terms of performance differences between separate components and the whole
Template to optimize
Vue also has the advantage of static optimization when using templates, which are optimized for template compilation in Vue3
React
Data-driven design
React update uses Virtual DOM to solve the problem of complete replacement during data update and realize the possibility of partial update. However, the layer of data update is weak, or we are completely unaware of the data change, so we need to take the initiative to setState. React introduced Fiber to optimize the performance of view updates. Here’s another important point: Time sharding. Vue3 originally implemented time sharding, but it was removed due to low revenue. This should be due to the advantages of Vue’s data-driven scheme, resulting in the lower benefits of time sharding
Template to optimize
JSX doesn’t provide enough information to optimize at compile time, but you can try to optimize the entire JSX compilation to React. CreateElement, and Currently FaceBook has launched Prepack for this optimization process
Angular
Data-driven design
Angular9 currently uses a combination of dirty detection and proxy, which is largely unused and not reviewed
Template to optimize
Angular supports templates, and with the release of V9, the Ivy rendering engine is available for optimization
Rethinking data-driven design
React is not really an MVVM framework. As it says, it is a view-level framework. There are different ways to implement data drive, and we can’t say which one is better or worse. Every data-driven approach has a bit of a flaw, and the framework itself is being optimized for those flaws
Componentized design
In addition to data-driven another front-end trend, how does the framework design components is also a concern
Vue
define
Vue.component("my-component", {
props: ['props1'].template: `
`.methods: {
clickHandler() {
this.$emit('click')}}});Copy the code
use
<my-component @click="clickHandler" :props1="props1" data-x="dataX">
<template #default>slot</template>
</my-component>
Copy the code
Data entry
Vue divides the props and attrs on the component. Inside the component, it provides the props option to capture the attr of the characteristics converted to props, and the rest becomes attrs attached directly to the root node of the component. In essence, this is the idea of default being greater than configuration. But there are always a few cases, so subsequent Vue provides inheritAttrs to control attR action elements
Component events
Vue’s events before the component are implemented using publish-subscribe EventEmitter, which has the following benefits over passing callbacks directly
- Cognitively, the trigger and responder are distinguished
Component content replacement
Vue provides a slot mechanism for providing nodes within an extension component, notably the scopedSlot mechanism
React
define
function Square(props) {
return (
<button onClick={props.onClick}>
{props.props1}
</button>
<div>props.slot<div>
);
}
Copy the code
use
<Square value={} onClick={() => this.handlerClick(i) slot={}}/>
Copy the code
Data entry
React doesn’t differentiate between Props and attrs, it just parses the data and gives the developer complete control
Component events
React uses the method of passing parent components directly into child components. I think EventEmitter like Vue is more developer-friendly
Component content replacement
React does not provide a special syntax for slot. Slot can be passed in as a normal property and the rest is handled internally by components
Angular
define
@Component({
/ / to omit
})
export class ProductAlertsComponent implements OnInit {
// Define the data entry
@Input() product;
// Define external events
@Output() notify = new EventEmitter();
constructor() {}}Copy the code
<div>
<button @click="notify.emit()"></button>
<ng-content></ng-content>
</div>
Copy the code
use
<component
(notify) ="onNotify()"
[product] ="product">
<div>slot</div>
</component>
Copy the code
Data entry
Angular simply provides a data entry point
Component events
Angular, like Vue, uses a publish-subscribe model to manage events between components
Component content replacement
Angular provides slot-like mechanisms to extend component node capabilities
Componentized design rethinking
There is no doubt that componentization must be the feature of the front-end framework in the future. How to design a good component is worth thinking about. The three frameworks also have their own thinking, which is not evaluated here
The framework characteristics
I think this point is just from my understanding, apart from data-driven and componentized design, framework has limited capabilities for developers. I don’t have a very in-depth analysis here
Vue
A lot of Vue features are developed from a developer perspective, such as attr and props. Angular and React are not handled this way. Developers are left to handle the details. Vue has built some developer-unfriendly processing into the framework
React
React design is to change developers and provide a powerful and complex mechanism. Of course, by doing this, the community will flourish and learn some good paradigms later on. At present, I am also learning React, and I have to say that React is more academic and the community can produce many good ideas
- Functional programming is favored
Angular
What impressed me most about Angular is the Service and DI mechanism. It also has a lot of consideration for developers. Many libraries can just use the official one, and the Angular scaffolding is comfortable to use
-
Service extracts logic unrelated to view rendering into separate code
-
DI solves the problem of confusing object management
-
Closer to Java OOP
conclusion
Starting from the problems solved by the front-end framework, we reflect on the necessary features of the framework, such as data-driven, componentization, without these two points, the rest of the framework features, the recommended programming paradigm is also worth our attention, such as Angular view rendering logic and data separation. We can also learn from React and Vue. Three framework in future to keep data driven and componentized features, framework features a piece, probably still need to a set of unified go, such as Vue3 hook and React hook, it is friendly to the developer, learning, cognitive cost less, and there will be someone in this article, who copy this kind of words, I think it is no good try, I want you to get a higher level view of the current development of the front end.