Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the differences between reactjs and vuejs

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Editor to share with you what are the differences between reactjs and vuejs, I hope you have something to gain after reading this article, let's discuss it together!

The difference between reactjs and vuejs: 1, vue is two-way data binding, react is not two-way binding; 2, non-parent and child components to achieve communication, react makes the common parent component trigger event function to transfer parameters, vue uses subscription / publish mode; 3, react uses Redux for state management, vue uses vuex.

The operating environment of this tutorial: windows7 system, vue2.9.6&&react16 version, DELL G3 computer.

Vue.js and React.js are very similar from some negative aspects. Through the study of the two frameworks, sometimes there is a little thought about some usage. In order to deepen the thinking of the study, I have flipped through two documents and made a comparison from the following aspects to deepen the understanding of the two frameworks.

1. Data binding

1.1 the section on data binding in Vue

Vue is bidirectional binding. There are two core functions of Vue.js, one is responsive data binding system, the other is component system. The so-called bi-directional binding means that the data in the vue instance is consistent with the content of the rendered DOM element, no matter who is changed, the other party will be updated to the same data accordingly. This is done by setting up a property accessor.

In vue, there are interpolation expressions, instruction sets, * Class and Style, event handlers and form spaces, ajax requests and evaluation properties related to data binding

1.1.1 interpolation expression

Interpolation and instructions are also known as template syntax

-the most common form of data binding is text interpolation using "Mustache" syntax (double curly braces)

-Mustache syntax cannot be applied to the HTML feature. In this case, the v-bind instruction should be used.

1.1.2 instruction

Instructions in vue are convenient, and instructions (Directives) are special attributes with a v-prefix. The value of the instruction property is expected to be a single JavaScript expression (v-for is an exception, which we'll discuss later). The responsibility of the instruction is to act responsively on the DOM when the value of the expression changes.

The 12 instructions in vue: vMutual bindline vMustonceGrammt vMutual ModellParticipityvMuturehtmlReagerVFFFLY, VELLBINDJEFFFFFF, vQEL, VELLBING, VLFLING, vLFLING, vLFLY, FLI, FLY, FLI, VLY, FLI, VL, QR, QR, M, F, P, R, C, Q, C, C,

1.1.3 class binds with style

A common requirement for data binding is the class list of operation elements and its inline style. Because they are all attributes, we can process them with v-bind: we just need to evaluate the final string of the expression. However, string concatenation is troublesome and error-prone. Therefore, when v-bind is used for class and style, Vue.js specifically enhances it. The result type of an expression can be an object or an array in addition to a string.

Object syntax

We can pass an object to v-bind:class to switch class dynamically

Array syntax

We can pass an array to v-bind:class to apply a class list:

1.1.4 conditional rendering and list rendering

A set of v-if conditional rendering

We use the v-for command to render based on a list of options in an array. The v-for instruction requires a special syntax in the form of item in items, where items is an array of source data and item is an alias for the iteration of array elements.

1.1.5 event handler

Register an event for an element through v-on

Using v-on has several benefits:

A glance at the HTML template makes it easy to locate the corresponding method in the JavaScript code.

Because you don't have to bind events manually in JavaScript, your ViewModel code can be very pure logic, completely decoupled from DOM, and easier to test.

When a ViewModel is destroyed, all event handlers are automatically deleted. You don't have to worry about how to clean them yourself.

1.1.6 form controls

V-model creates bidirectional data binding on form control elements

It automatically selects the correct method to update the element based on the control type.

1.1.7 calculation Properties

Computing attributes are introduced in Vue to deal with the problem that putting too much logic in the template will make the template overweight and difficult to maintain, which not only solves the above problems, but also makes the template and business logic better separated.

To put it simply, if there is an attribute adep1 in data, and then you need a variable to change with a, such as b=a+1, then you need to calculate the property. In the computed property of the Vue instance, set b as its property, which behaves as a function, and the return value is the value of b.

1.1.8 ajax data request

Axios is recommended for data requests in vue2.0

Note: two-way data binding and one-way data flow for vue

Vue's dependency tracking is [in principle does not support two-way binding, v-model is just a grammatical sugar realized by listening for DOM events]

The dependency tracking of vue is realized by converting all the properties of the data object into getter/setter through Object.defineProperty; when changing a property value of the data, the set function will be triggered, and when the attribute value is obtained, the get function will be triggered, which can be used to change the view when changing the data. That is to say, only when the data changes, the view change will be triggered. On the contrary, when you manipulate the view, you can only change the data through the DOM event, and then change the view, so as to achieve two-way binding.

Two-way binding binds data and views within the same component and has nothing to do with the communication between parent and child components.

One-way data flow is used for better decoupling between components. In development, multiple child components may depend on some data of the parent component. If the child component can modify the data of the parent component, a change in a child component will cause changes in all the child components that depend on this data, so vue does not recommend the child component to modify the data of the parent component. Modifying the props directly will throw a warning.

1.2 react has no two-way data binding

React is a unidirectional data stream

In react, the state (Model layer) and view layer data are bidirectionally bound to achieve real-time data update changes. Specifically, the data in the JS layer is directly written in the View layer and rendered. Once the data changes are triggered, such as form operations, trigger events, ajax requests, etc., double synchronization is carried out.

1.2.1 event handling

The event handling of the React element is very similar to that of the DOM element. But there is one grammatical difference:

React event binding properties are named in hump style rather than lowercase.

If you use the syntax of JSX, you need to pass in a function as an event handler instead of a string (DOM element)

Another difference in React is that you cannot block the default behavior by returning false. You must explicitly use preventDefault.

When you use ES6 class syntax to define a component, the event handler becomes a method of the class. Explicit binding of this is generally required, such as

This.handleClick = this.handleClick.bind (this)

You must be careful with the this in the JSX callback function. The methods of the class are not bound to this by default. If you forget to bind this.handleClick and pass it into onClick, the value of this will be undefined when you call this function.

1.2.2 conditional rendering

Conditional rendering in React is consistent with that in JavaScript, using the JavaScript operator if or conditional operator to create elements that represent the current state, and then have React update the UI based on them.

You can embed any expression in JSX by wrapping code in curly braces, including JavaScript logic and & &, which can easily render an element conditionally. You can do this because in JavaScript, true & & expression always returns expression, while false & & expression always returns false. Therefore, if the condition is true,&&, the element to the right will be rendered, and if it is false,React, it will be ignored and skipped.

Another method of conditional rendering is to use JavaScript's conditional operator condition? True: false .

1.2.3 list rendering

You can use {} to build a collection of elements within JSX and use the map () method in Javascript to iterate through the array

Keys can help React identify which elements have changed when some elements in DOM are added or deleted. So you should assign a definite identity to each element in the array. The key of an element is preferably a unique string that the element has in the list. Typically, we use the id from the data as the key of the element.

1.2.4 form actions

HTML form elements are different from other DOM elements in React because form elements are born with some internal state.

When a user submits a form, the default behavior of HTML causes the form to jump to a new page. The same is true in React. In most cases, however, we construct a function that handles the submission of the form and accesses the data entered by the user. The standard way to do this is to use a technology called "controlled components". Input form elements whose values are controlled by React are called "controlled components". This.setState ({value: event.target.value})

When you have multiple controlled input elements, you can let the handler choose what to do based on the value of the event.target.name by adding a name attribute to each element.

1.2.5 status improvement

In React, state sharing is done by promoting state data to the parent component closest to the component that needs it. This is called state promotion. This.props.xxx

In React applications, there should be only a single "data source" for any variable data. Typically, states are first added to the components that need to render data. At this point, if another component also needs this data, you can promote the data to the nearest parent component. Instead of trying to synchronize state in different components, you should maintain a top-down data flow in your application.

two。 Componentization and component data flow

2.1 components and data flows in react

React is an one-way data flow, and the data is mainly passed from the parent node to the child node (through the props). If a props at the top level (parent) changes, React re-renders all child nodes.

There are two ways to implement components in react, one is the createClass method, and the other is that the thought class of ES2015 inherits React.Component.

In React applications, buttons, forms, dialogs, the contents of the entire screen, and so on, are usually represented as components.

React advocates functional programming and one-way data flow: given the original interface (or data), applying a change can deduce another state (update of the interface or data).

Components can split the UI into separate, reusable parts, so you only need to focus on building each individual part. A component is conceptually like a function that can take any input value (called "props") and return a React element that needs to be displayed on the page.

1. Read-only property of Props

Whether you use a function or a class to declare a component, it must never modify its own props.

All React components must use their props like pure functions.

The difference between props and State

-props is the abbreviation of property and can be understood as the attribute of the HTML tag. You cannot use this.props to modify props directly because props is read-only and props is used to pass data and configuration throughout the component tree. Access props in the current component and use this.props.

-props is a setting parameter for a component that can be set selectively in the parent control. The parent component assigns a value to the props of the child control, and the value of props is immutable. A child control itself cannot change its own props.

-state: when a component mounts, state will be used if the default value is set, and state may be changed from time to time. A child control can manage its own state, but it is important to note that you cannot manage the state of its child controls. So it can be considered that the state is private to the child control itself.

-each component has its own state,state and props, the difference is that the former (state) only exists within the component, can only call this.setState from the current component to modify the state value (you can not modify this.state directly! ).

-props is a data stream passed from a parent component to a child component, which can be passed to the descendant component all the time. However, state represents the internal state of the subcomponent itself. Semantically, changing the state of a component may lead to a change in the structure of the dom or re-rendering. Props is the parameter passed by the parent component, so it can be used to initialize rendering and change the state of the component itself, although most of the time the state of the component is changed by external events. What we need to know is that the render method may be executed whether it is a state change or a props change passed by the parent component.

Generally speaking, we update the subcomponents by changing the state value and updating the props value of the new subcomponents.

2.1.1 Communication between components

1. Communication between parent and child components

The props attribute is passed between parent and child.

Between the child and the parent, the parent component defines the event, and when the child component triggers the event in the parent component, it communicates by changing the data in the parent component in the form of arguments

That is:

-* parent component updates component status-- props-- > child component update

-* Child component updates the status of the parent component-- requires the parent component to pass a callback function-- > the child component call triggers

2. The communication between non-parent and child components, which are not deeply nested, can be realized by triggering event functions to transfer formal parameters to the common parent components.

Sibling components:

(1) according to the React unidirectional data flow mode, we need to pass it with the help of the parent component, and change the props of the sibling component through the callback function of the parent component.

-in fact, this implementation is more or less the same as the way the child component updates the status of the parent component.

(2) when the component level is very deep, here, React officially provides us with a context way, which allows sub-components to access ancestral data or functions directly, without the need to transfer data from ancestral components to subcomponents layer by layer.

2.1.2 Lifecycle of components

Construtor () / create component componentWillMount () / / componentDidMount () before component mount / / after component mount componentWillReceiveProps () / / when render occurs in the parent component, the child component calls the function shouldComponentUpdate () / / after each call to setState to determine whether the component needs to be re-rendered. Default returns truecomponentDidUpdate () / / update render () / / render The core function componentWillUnmount () / / in react is called when the component is uninstalled. Generally, events registered in componentDidMount need to be deleted here.

2.2 components and data flows in vue

2.2.1 component-based application construction

Component systems are another important concept of Vue because it is an abstraction that allows us to build large applications using small, independent, and often reusable components.

In Vue, a component is essentially an instance of Vue with predefined options

In a large application, it is necessary to divide the entire application into components to make the development manageable.

Component (component) is one of the most powerful features of Vue. Components can help you extend basic HTML elements to encapsulate reusable code. At a higher level, components are custom elements that the Vue compiler appends to its behavior. In some cases, components can also be in the form of native HTML elements that extend with specific is features.

In a component, data must be a function

Components can extend HTML elements to encapsulate reusable code. At a higher level, components are custom elements, and Vue.js 's compiler adds special functionality to it. In some cases, components can also be in the form of native HTML elements, extending with the is feature.

2.2.2 responsive

When a Vue instance is created, it adds all the properties that can be found in its data object to Vue's responsive system. When the values of these properties change, the view will produce a "response", that is, the match will be updated to the new value.

When the data changes, the view is re-rendered. It is worth noting that only the properties that exist in the data when the instance is created are responsive.

2.2.3 Lifecycle of components

Each Vue instance goes through a series of initialization processes before it is created. For example, you need to set up data listening, compile templates, mount instances to DOM, update DOM when data changes, and so on. At the same time, some functions called lifecycle hooks are run in the process, giving users the opportunity to add their own code in certain scenarios.

For example, created hooks can be used to execute code after an instance is created, and there are other hooks that can be called in different scenarios of the instance lifecycle, such as mounted, updated, destroyed. The this of the hook points to the Vue instance that called it.

Lifecycle diagram:

2.2.3 Communication between components

Vue defaults to unidirectional data flow, which is stated directly by Vue, and the parent component can pass data to the child component by default, but the child component passing data to the parent component requires additional settings.

Vue also supports two-way binding, which defaults to one-way binding, and data is passed one-way from the parent component to the child component. The use of unidirectional binding in large applications makes the data flow easy to understand.

Data communication between parent and child components is achieved through Prop and custom events, while non-parent / child components can use the subscription / publish pattern (similar to communication between non-parent and child instructions in Angualr), and state management (vuex) is recommended.

In Vue, the relationship between parent and child components can be summarized as follows: props down, events up. The parent component passes data down to the child component through props, and the child component sends messages to the parent component through events.

1. Father to son

-each component instance has its own isolated scope. That is, parent component data cannot (and should not) be referenced directly in the child component template. To reference the parent component data in the child component template, you can use props to pass the data down to the child component.

-each prop property controls whether data is received from the custom property of the parent component. The child component needs to explicitly declare the props using the props option so that it can receive the desired data from the parent component.

-dynamic Props, similar to binding a normal property to an expression, we can also use v-bind to dynamically bind the props attribute to the data in the parent component. Whenever the parent component updates the data, it can flow down into the child component

two。 The son to the father

-use custom events

-each Vue instance is connected to an event API (events interface), that is, these Vue instances can:

-use on (eventName) to listen for an event − uses emit (eventName) to trigger an event

3. Non-parent-child component communication

-you can use an empty Vue instance as an event bus center (central event bus), use emit to trigger events, and on to listen for events

3. State management

State Management in react: Flux

Redux is the most popular Flux implementation in React ecological environment. Redux is virtually insensitive to the view layer, so it can be easily used with Vue through some simple bindings.

Create actions

Create store

Create dispatcher

Call methods in action in the view layer

Is all kinds of component.

The method in dispatcher to note the corresponding store for each action through register

Store contains the state and logic of the application, which is used to manage different states and logic in the application, which is equivalent to the Model layer.

Define actions. Event triggers need to be called with dispatcher

Behaviors, such as add operations, delete operations, and update operations, are a bunch of functions.

3.2 State Management vuex in vue

Vuex borrows from Flux, Redux, and The Elm Architecture. Unlike other patterns, Vuex is a state management library specially designed for Vue.js to take advantage of Vue.js 's fine-grained data response mechanism for efficient state updates. This allows it to better integrate with Vue while providing a concise API and an improved development experience.

The component does not allow direct modification of the state belonging to the store instance, but instead executes action to dispatch the event notification store to change, and we finally reach the Flux architecture. The advantage of this engagement is that we can record all state changes that occur in store and implement advanced debugging tools that can record changes (mutation), save state snapshots, and history rollback / time travel.

The core of every Vuex application is store. "store" is basically a container that contains most of the state in your application.

A Vuex differs from a simple global object in the following two ways:

1. The state storage of Vuex is responsive. When the Vue component reads the state from the store, if the state in the store changes, then the corresponding component will be updated efficiently accordingly.

2. You can't directly change the state in store. The only way to change the state in store is to commit the mutation explicitly. This makes it easy for us to track changes in each state, allowing us to implement tools to help us better understand our applications.

3 、 State

Vuex uses a single state tree-yes, all application-level states are contained in a single object. At this point, it exists as a "unique data source (SSOT)". This also means that each application will contain only one instance of store. A single state tree enables us to directly locate any specific state fragment and easily take a snapshot of the entire current application state in the process of debugging. This also means that each application will contain only one instance of store.

To get status values from state, sometimes we need to derive states from state in store, such as filtering and counting lists.

1 、 Mutation

2 、 Action

3 、 Module

Action is similar to mutation, except that:

Action submits the mutation instead of directly changing the state.

Action can contain any asynchronous operation.

Dispatch Distribution action

The only way to change the state in the store of the Vuex is to commit the mutation. Mutation in Vuex is very similar to events: each mutation has an event type of a string (type) and a callback function (handler). This callback function is where we actually make the state change, and it accepts state as the first argument.

You can't call a mutation handler directly. This option is more like event registration: "this function is called when a mutation of type increment is triggered." To wake up a mutation handler, you need to call the store.commit method with the appropriate type

Due to the use of a single state tree, all the states of the application are concentrated in a larger object. When applications become very complex, store objects are likely to become quite bloated.

Vuex allows us to split store into modules (module). Each module has its own state, mutation, action, getter, or even nested submodules-- split in the same way from top to bottom

4. Routin

The routes of the two are very similar, and both use the idea of componentization.

4.1 routing in react

When it comes to routing repositories, React chooses to leave the problem to the community for maintenance, thus creating a more decentralized ecosystem. But in contrast, React's ecosystem is more prosperous than Vue's.

In react, react-router library needs to be introduced.

When in use, router Router is a component of React.

The Router component itself is just a container, and the real routing is defined by the Route component.

The Route component defines the correspondence between the URL path and the component. You can use multiple Route components at the same time.

The-Link component is used to replace the element and generate a link that allows the user to click and jump to another route. It is basically the React version of the element and can receive the state of the Router.

4.2 routing in vue

Vue's routing library and state management library are supported by official maintenance and updated synchronously with the core library.

With Vue.js, we can already compose applications by combining components, and when you want to add vue-router, what we need to do is map components (components) to routes, and then tell vue-router where to render them.

In HTML:

Hello App!

Go to Foo Go to Bar

5. Rendering performance comparison

In the operating interface, to minimize the operation of DOM, Vue and React are implemented using virtual DOM, and both work equally well.

Minimize operations other than DOM operations. (the difference between vue and react)

5.1 react View rendering

React rendering is based on Virtual DOM, a data structure that describes the state of the DOM tree in memory. When the state changes, React renders the Virtual DOM again and patches the real DOM after comparison calculation.

Virtual DOM provides a functional way to describe the view, it does not use the data observation mechanism, each update will re-render the entire application, so by definition to ensure the synchronization of the view and data. It also opens up the possibility of JavaScript isomorphic applications.

React has certain advantages in the rendering speed of the first screen of a large amount of data, because the rendering mechanism of Vue needs to do a lot of work when it starts, and React supports server-side rendering.

Elements are the smallest units that make up a React application. Elements are used to describe what you see on the screen. Unlike the DOM element in the browser, the elements in React are actually ordinary objects. React DOM ensures that the data content of the browser DOM is consistent with the React element.

When we develop applications with React, we usually define only one root node. But if you are introducing React into an existing project, you may need to define the React root node separately in different parts. We pass an element into a method called ReactDOM.render () to render it to the page, and the element is displayed on the page.

Component rendering

-when the element React encounters is a user-defined component, it passes the JSX attribute to the component as a single object, which is called "props".

5.2 vue view rendering

Vue keeps track of changes that have taken place in the real DOM by creating a virtual DOM.

The process of vue rendering is as follows:

New Vue, perform initialization

Load the $mount method, and generate the Render function through custom Render method, template, el, etc.

Listen for changes in data through Watcher

When the data changes, the Render function executes to generate the VNode object

Through the patch method, comparing the new and old VNode objects, and through the DOM Diff algorithm, add, modify and delete the real DOM elements

6. Data update

6.1 react data updates

React elements are immutable immutable. After an element is created, you cannot change its contents or attributes. An element is like a frame in an animation that represents what the application interface looks like at a certain point in time.

Based on what we know about React at this stage, the only way to update the interface is to create a new element and pass it into the ReactDOM.render () method

6.2 vue data updates

7. Development mode and scale

7.1 react

7.1.1 Development model

React itself, is a strict view layer, MVC mode

7.1.2 scale

Vue provides Vue-cli scaffolding, which makes it very easy to build projects, including Webpack,Browserify and even no build system.

7.2 vue

7.2.1 Development model

Vue is a way to implement the MVVM pattern

Although it does not fully follow the MVVM model, the design of Vue is undoubtedly inspired by it. Therefore, the variable name vm (short for ViewModel) is often used in documents to represent Vue instances.

7.2.2 scaffolding

React provides create-react-app, but now there are some limitations:

It does not allow any configuration at project build time, while Vue supports Yeoman-like customization.

It only provides a single template for building single-page applications, while Vue provides templates for a variety of purposes.

It cannot build projects with user-built templates, which are particularly useful for pre-establishing protocols in an enterprise environment.

8. HTML&&CSS

In React, everything is JavaScript. Not only can HTML be expressed in JSX, but the current trend is increasingly to incorporate CSS into JavaScript. This type of solution has its advantages, but there are also some trade-offs that are not acceptable to every developer.

The whole idea of Vue is to embrace the classic Web technology and extend it.

8.1 react

8.1.1 JSX

In React, the rendering capabilities of all components depend on JSX. JSX is a grammatical sugar for writing JavaScript using XML syntax.

JSX, a syntax extension of JavaScript. We recommend using JSX in React to describe the user interface. JSX may seem more like a template language at first glance, but in fact it is implemented entirely within JavaScript.

JSX is used to declare elements in React.

JSX itself is also an expression, and after compilation, JSX is actually converted into a normal JavaScript object. This means that you can actually use JSX in if or for statements, assign it to a variable, pass it as a parameter, or as a return value.

JSX says that handwritten rendering functions have the following advantages:

You can use the full programming language JavaScript function to build your view page. For example, you can use temporary variables, flow controls that come with JS, and directly refer to values in the current JS scope, and so on.

The development tool's support for JSX is more advanced than other available Vue templates (for example, linting, type checking, editor autocompletion).

8.1.2 CSS within the scope of a component

Unless you distribute components across multiple files (such as CSS Modules), CSS scopes are implemented in React through CSS-in-JS solutions (such as styled-components, glamorous, and emotion). This introduces a new component-oriented style paradigm, which is different from the normal CSS writing process. In addition, although it is supported to extract CSS into a separate stylesheet at build time, a runtime program is usually needed in bundle for these styles to take effect. While you can handle styles flexibly with JavaScript, you also need to weigh the size of bundle against runtime overhead.

8.2 vue

8.2.1 Templates template syntax

In fact, Vue also provides rendering functions and even supports JSX. However, we recommend templates by default. Any HTML that conforms to the specification is a legitimate Vue template, which brings some unique advantages:

For many developers who are used to HTML, templates are more natural to read and write than JSX. There is, of course, an element of subjective preference, but if this difference leads to an increase in development efficiency, then it has objective value.

HTML-based templates make it easier to gradually migrate existing applications to Vue.

It also makes it easier for designers and new developers to understand and participate in the project.

You can even use other template preprocessors, such as Pug, to write templates for Vue.

Vue.js uses HTML-based template syntax, which allows developers to declaratively bind DOM to the data of the underlying Vue instance. All Vue.js templates are legitimate HTML, so they can be parsed by specification-compliant browsers and HTML parsers.

In the underlying implementation, Vue compiles the template into a virtual DOM rendering function. Combined with the response system, when the application state changes, Vue can intelligently calculate the minimum cost of re-rendering components and apply it to DOM operations.

8.2.2 single file component CSS

The default method for Vue styling is a style-like tag in a single-file component.

The single-file component gives you complete control over CSS in the same file as part of the component code.

The styling in the single file component of Vue is very flexible. With vue-loader, you can use any preprocessor, post-processor, or even deeply integrated CSS Modules--, all in

8.3 Summary

From a more abstract point of view, we can divide components into two categories: one is presentational, and the other is logical. We recommend using templates in the former and JSX or rendering functions in the latter. The proportion of these two types of components varies depending on the type of application, but on the whole, we find that there are far more components representing classes than logical components.

9. Working with scen

9.1 Select react

9.1.1 looking forward to building a large application-- choose React

Simple applications implemented in both Vue and React may make a developer subconsciously more inclined to Vue. This is because template-based applications look easier to understand at first glance and can run quickly. But the technical debt introduced by these benefits will prevent the application from expanding to a larger scale. Templates are prone to runtime errors that are difficult to notice, and it is also difficult to test, ReFactor, and decompose.

In contrast, Javascript templates can be organized into components with good decomposability and DRY code, which are more reusable and testable. Vue also has component systems and rendering functions, but React's rendering system is more configurable and has features such as shallow rendering, which are used in conjunction with React's testing tools to make the code more testable and maintainable.

At the same time, React's immutable application status may not be concise enough to write, but it makes sense in large applications because transparency and testability become critical in large projects.

9.1.2 looking forward to a framework suitable for both web-side and native APP-- choose React

React Native is a library that uses Javascript to build mobile native applications (iOS,Android). It is the same as React.js, except that instead of using Web components, it uses native components. If you have studied React.js, you will soon be able to use React Native, and vice versa.

Its significance is that developers only need a set of knowledge and tools to develop Web applications and mobile native applications. If you want to do both Web development and mobile development, React has a big gift for you.

Ali's Weex is also a cross-platform UI project, which is currently inspired by Vue, uses many of the same syntax, and plans to fully integrate Vue in the future, but the timing and details of the integration are unclear. Because Vue takes the HTML template as the core of its design, and the existing features do not support custom rendering, it is difficult to see that the current cross-platform capabilities of Vue.js are as powerful as React and React Native.

9.1.3 look forward to the largest ecosystem-choose React

There is no doubt that React is by far the most popular front-end framework. It is downloaded more than 2.5 million times a month on NPM, compared with 225000 for Vue. Popularity is not just a superficial number, it means more articles, tutorials and more Stack Overflow solutions, but also more tools and plug-ins that can be used in projects, so that developers are no longer isolated.

Both frameworks are open source, but React was born in Facebook, endorsed by Facebook, and its developers and Facebook are committed to maintaining React on a continuous basis. By contrast, Vue is the work of independent developer you Yuxi. You Yuxi is currently maintaining Vue full-time, and there are some companies that fund Vue, but the scale is not comparable to that of Facebook and Google. But rest assured that Vue's team is not at a disadvantage because of its small size and independence. Vue has a fixed release cycle, and even more laudably, there are only 54 open issue,3456 closed issue on Vue on Github, compared with as many as 530 open issue,3447 closed issue in React.

9.2 Select vue

9.2.1 look forward to template building applications-select Vue

The default option for Vue applications is to put markup in the HTML file. Data-binding expressions use mustache syntax similar to Angular, while instructions (special HTML attributes) are used to add functionality to templates.

By contrast, React applications do not use templates, which require developers to create DOM in JavaScript with the help of JSX.

Templates are easier to understand for new developers from standard Web development methods. But some experienced developers also like templates because they can better separate layouts from functions, and can also use template engines such as Pug.

But the cost of using templates is that you have to learn all the HTML extension syntax, while rendering functions only need to know the standard HTML and JavaScript. And rendering functions are easier to debug and test than templates. Of course, you should not miss Vue for this reason, because Vue2.0 provides the option of using templates or rendering functions.

9.2.2 expect something simple and "as long as you can use it"-choose Vue

A simple Vue project can run directly in a browser without translation, so using Vue can be as simple as using jQuery. Of course, this is also technically feasible for React, but typical React code relies heavily on JSX and ES6 features such as class.

The simplicity of Vue is deeper in programming, so let's compare how the two frameworks deal with application data (that is, state).

React determines when to re-render and what to render in DOM by comparing the current state with the previous state, so an immutable (immutable) state is required.

The data in Vue is mutated, so the same operation looks more concise.

Let's take a look at how state management is done in Vue. When you add a new object to state, Vue iterates through all the properties in it and converts it to getter,setter methods. Now Vue's response system starts to keep track of state, and automatically renders DOM when the content in state changes. Commendably, the operation of changing the state of state in Vue is not only simpler, but its re-rendering system is faster and more efficient than React's.

There are some pitfalls in Vue's response system, for example, it cannot detect the addition and deletion of attributes and some array changes. At this point, the set method similar to React in Vue API will be used to solve the problem.

9.2.3 expect applications to be as small and fast as possible-choose Vue

When the state of the application changes, both React and Vue will build a virtual DOM and synchronize it into the real DOM. Both have their own ways to optimize this process.

The core developers of Vue provide a benchmark test, and you can see that Vue's rendering system is faster than React's. The test method is to render a list of 10000 projects 100 times, and the result is shown in the following figure. From a practical point of view, this benchmark is only related to marginal situations, and this is not often done in most applications, so this should not be seen as an important point of comparison. However, the page size is related to all projects, and Vue leads again in this respect, and its current version is compressed with only 25.6KB. To achieve the same function in React, you need React DOM (37.4KB) and React with Addon library (11.4KB), which add up to 44.8KB, which is almost twice the size of Vue. Double volume does not bring double function.

Server side rendering ssr "> 10. Server side rendering (SSR)

Client rendering route: 1. Request a html-> 2. The server returns a html-> 3. Browser downloads the js/css file in html-> 4. Wait for the js file download to complete-> 5. Wait for js to load and initialize-> 6. The js code can finally run, and the js code requests data (ajax/fetch) from the backend-> 7. Wait for the backend data to return-> 8. React-dom (client) renders the data as a response page from nothing to the whole

Server rendering route: 1. Request a html-> 2. Server request data (intranet request fast)-> 3. Server initial rendering (server performance is good, fast)-> 4. The server returns the page with the correct content-> 5. Client requests js/css file-> 6. Wait for the js file download to complete-> 7. Wait for js to load and initialize-> 8. React-dom (client) finishes rendering the rest (small content, fast rendering)

10.1 react

React's virtual DOM is the key that it can be used for server-side rendering. First, each ReactComponent is rendered in the virtual DOM, and then the React updates the changed part of the browser DOM through the virtual DOM. As a DOM representation in memory, the virtual DOM provides you with the possibility of sucking React in a non-browser environment such as Node.js. React can generate a string from the virtual DoM. Instead of the new real DOM, this allows us to use the same React Component on both the client and the server.

React provides two functions that are available for server-side rendering components: React.renderToString and React.render-ToStaticMarkup. When designing ReactComponent for server-side rendering, you need to be predictable, considering the following aspects.

Select the best rendering function.

How to support the asynchronous state of components.

How to pass the initialization state of the application to the client.

Which lifecycle functions can be used for server-side rendering.

How to provide homogeneous routing support for applications.

The use of singletons, instances, and context.

10.2 vue

1. What is server-side rendering (SSR)?

Vue.js is the framework for building client applications. By default, you can output Vue components in a browser to generate DOM and manipulate DOM. However, you can also render the same component as server-side HTML strings, send them directly to the browser, and finally "mix" the static tags into a fully interactive application on the client side.

Server-rendered Vue.js applications can also be considered "homogeneous" or "generic" because most of the application's code can be run on both the server and the client.

two。 Server-side rendering advantage

-better SEO, because the search engine crawler crawler can view fully rendered pages directly.

-faster content arrival time (time-to-content), especially for slow network conditions or slow-running devices. You don't have to wait for all the JavaScript to be downloaded and executed before the server-rendered markup is displayed, so your users will see the fully rendered page more quickly. It usually produces a better user experience, and server-side rendering (SSR) is critical for applications where content time-to-arrival (time-to-content) is directly related to conversion.

11. Attached: react concept

1. Divide the UI diagram into component levels

two。 Create a static version with React

Pass in the data model and render the UI without any interaction. It's best to decouple these processes, because creating a static version requires more code than logical thinking, while adding interaction requires more logical thinking than code.

Do not use state when creating a static version.

You can build applications from top to bottom or bottom up. That is, you can start with the highest-level components (that is, FilterableProductTable) or the lowest-level components (ProductRow). In simpler cases, top-down is usually easier, while in larger projects, bottom-up is easier and makes it easier to write tests when you build.

React's unidirectional data flow (also known as unidirectional binding) ensures that everything is modular and fast.

3. Define the smallest (but complete) representation of the UI state

Thinking about the data in the example application, let's look at each one and find out which one is state. There are only three questions to consider for each data:

Is it coming from the parent through props? If so, he may not be state.

Does it stay the same over time? If so, it may not be state.

Can you calculate it based on any other state or props in the component? If so, it is not a state.

4. Determine where your State should be located

For every state you apply:

Identify each component that needs this state to render.

Find a common owner component (a component that is hierarchically higher than all other components that need this state)

This common owner component or another higher-level component should have this state.

If you don't find a component that can own the state, create a component that is only used to save state and add it to a higher level than the common owner component.

5. Add reverse data flow

Summary

To sum up, we found that

The benefits of Vue include:

-flexible selection of templates and rendering functions

-simple syntax and project creation

-faster rendering speed and smaller volume

The benefits of React include:

-more suitable for large applications and better testability

-suitable for both web-side and native App

-more support and tools from a larger biosphere

In fact, React and Vue are both excellent frameworks, with more similarities than differences, and most of their best features are the same:

-using virtual DOM to realize fast rendering

-lightweight

-responsive and componentized

-Server-side rendering

-easy to integrate routing tools, packaging tools, and state management tools

-excellent support and community

After reading this article, I believe you have a certain understanding of "what are the differences between reactjs and vuejs". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report