Home  >  Article  >  Web Front-end  >  What is the difference between reactjs and vuejs

What is the difference between reactjs and vuejs

青灯夜游
青灯夜游Original
2021-09-01 11:37:363450browse

The difference between reactjs and vuejs: 1. Vue is a two-way binding of data, while react is not a two-way binding; 2. Non-parent and child components implement communication, and react enables the common parent component to trigger event functions to pass formal parameters, while vue Use the subscription/publish mode; 3. React uses Redux for state management, and Vue uses vuex.

What is the difference between reactjs and vuejs

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

Vue.js and React.js are very similar in some aspects. Through learning the two frameworks, sometimes I have a little thought about some usages. In order to deepen my thoughts on learning, I read the two The document compares the following aspects to deepen the understanding of the two frameworks.

1. Data binding

1.1 Parts about data binding in Vue

  • Vue is a two-way binding. There are two core functions of Vue.js. One is the responsive data binding system, and the other is the component system. The so-called two-way binding means that the data in the Vue instance is consistent with the content of the DOM element it renders. No matter who is changed, the other party will be updated to the same data accordingly. This is accomplished by setting property accessors.
  • In vue, data binding is related to interpolation expressions, command systems, *Class and Style, event handlers and form spaces, ajax requests and calculated properties

1.1.1 Interpolation expressions

Interpolation and directives are also called template syntax
- The most common form of data binding is to use the "Mustache" syntax ( Text interpolation of double braces)
- Mustache syntax cannot be used on HTML features. In this case, the v-bind directive should be used

1.1.2 Directive

  • #Directives in vue are very convenient. Directives are special attributes with v- prefix. The value of a directive attribute is expected to be a single JavaScript expression (v-for is the exception, which we'll discuss later). The responsibility of the directive is to reactively apply its associated effects to the DOM when the value of the expression changes.

  • 12 instructions in vue: v-bind,v-once,v-model,v-text,v-html,v-on,v-if, v-else,v-show,v-for,v-pre,v-clock

##1.1.3 Class and style binding

    A common requirement for data binding is to manipulate an element's class list and its inline styles. Since they are all properties, we can use v-bind to handle them: we just need to evaluate the final string of the expression. However, string concatenation is cumbersome and error-prone. Therefore, Vue.js specifically enhances v-bind when used with classes and styles. In addition to strings, the result type of an expression can also be an object or an array.
  • Object syntax

    • We can pass an object to v-bind:class to dynamically switch classes
  • Array syntax

    • We can pass an array to v-bind:class to apply a class list:
  • <div v-bind:class="[activeClass, errorClass]"></div>

1.1.4 Conditional rendering And list rendering

    v-if conditional rendering of a set of numbers
  • We use the v-for instruction to render based on a list of options in an array. The v-for directive requires special syntax of the form item in items, where items is the source data array and item is an alias for iterating over the array elements.

1.1.5 Event handler

    Register events to elements through v-on
  • There are several ways to use v-on One benefit:

    • You can easily locate the corresponding method in the JavaScript code by scanning the HTML template.
    • Because you don’t need to manually bind events in JavaScript, your ViewModel code can be very pure logic, completely decoupled from the DOM, and easier to test.
    • When a ViewModel is destroyed, all event handlers will be automatically deleted. You don’t have to worry about cleaning them yourself.

1.1.6 Form Control

    v-model creates two-way data binding on the form control element
  • It will automatically select the correct method to update the element based on the control type.

1.1.7 Computed properties

    Computed properties are introduced in Vue to deal with the problem that putting too much logic in the template will make the template pass. It is heavy and difficult to maintain. This not only solves the above problems, but also allows for a better separation of templates and business logic.
  • Simply put, if there is an attribute a=1 in the data, and then you need a variable to change with a, for example, b=a 1, then you need to use the calculated attribute. In the computed attribute of the Vue instance, set b is its attribute, it behaves as a function, and the return value is the value of b.

1.1.8 ajax data request

    It is recommended to use axios for data requests in vue2.0
Note:
About vue’s two-way data binding and one-way data flow
  • Vue’s dependency tracking is [in principle, two-way binding is not supported, v-model It’s just syntactic sugar implemented by listening to DOM events]

  • Vue's dependency tracking is implemented by converting all the properties of the data object into getters/setters through Object.defineProperty; when a property value of the data is changed, the set function will be triggered to obtain the The get function will be triggered when the attribute value is changed. Through this feature, the view can be changed when the data is changed; that is to say, the view change will only be triggered when the data changes. Conversely, when the view is operated, the data can only be changed through DOM events. , and then change the view to achieve two-way binding

  • Two-way binding is to bind data and view within the same component, and between parent and child components There is no connection with the communication;
  • The communication between components uses One-way data flow is for better decoupling between components. There may be multiple sub-components during development Depends on certain data of the parent component. If the child component can modify the data of the parent component, a change in the child component will cause changes in all child components that rely on this data. Therefore, Vue does not recommend that child components modify the data of the parent component and modify props directly. A warning will be thrown

1.2 react does not have two-way data binding

  • react is a one-way data flow
  • React achieves real-time updates and changes of data by bidirectionally binding state (Model layer) and View layer data. Specifically, writing JS code directly in the View layer takes the data in the Model layer and renders it. Once it is like Form operations, trigger events, ajax requests, etc. trigger data changes, then dual synchronization is performed

1.2.1 Event processing

  • The event handling of React elements is very similar to that of DOM elements. But there is a little grammatical difference:

    • React event binding properties are named in camel case instead of lower case.
    • If you use JSX syntax, you need to pass in a function as an event handler, rather than a string (the way DOM elements are written)
    • Another difference in React is that you cannot use return false to prevent the default behavior. You must use preventDefault explicitly.
    • When you use ES6 class syntax to define a component, the event handler becomes a method of the class. Generally you need to explicitly bind this, for example

      this.handleClick = this.handleClick.bind(this);

    • You must treat JSX callbacks with caution This in functions and class methods will not be 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 the same as in JavaScript, using JavaScript operators if or conditional operators to create elements that represent the current state and let React update the UI based on them.
  • You can embed any expression in JSX by wrapping the code with curly braces, including JavaScript logic and &&, which can conveniently render an element conditionally. This works because in JavaScript, true && expression always returns expression, and false && expression always returns false. So, if the condition is true, the element to the right of && will be rendered, if it's false, React will ignore it and skip it.
  • Another method of conditional rendering is to use JavaScript’s conditional operator condition ? true : false .

1.2.3 List Rendering

  • You can build a collection of elements within JSX by using {}, using map() in Javascript The method loops through the array
  • Keys can help React identify which elements have changed when certain elements in the DOM are added or deleted. Therefore you should give each element in the array a certain identity. The key of an element is preferably a unique string owned by this element in the list. Typically, we use the id from the data as the key for the element.

1.2.4 Form operations

  • HTML form elements are different from other DOM elements in React because form elements are inherently reserved 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. But most of the time, we will construct a function that handles submitting the form and has access to the user-entered form data. The standard way to achieve this is to use a technique 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 add a name to each element Attribute to let the handler choose what to do based on the value of event.target.name.

1.2.5 Status improvement

  • In React, state sharing is accomplished by promoting state data to the parent component closest to the component that needs the data. This is called status improvement. this.props.xxx
  • In a React application, there should be only a single "data source" for any mutable data. Usually, state is added first to the component that needs to render data. At this point, if another component also needs the data, you can lift the data to their nearest parent component. You should maintain a top-down flow of data in your application rather than trying to synchronize state among different components.

2. Componentization and component data flow

2.1 Components and data flow in react

  • React is a one-way data flow, and data is mainly passed from parent nodes to child nodes (through props). If one of the top-level (parent) props changes, React will re-render all child nodes.
  • There are two ways to implement components in react, one is the createClass method, and the other is implemented by inheriting React.Component through the ES2015 ideological class
  • In React applications, buttons, Forms, dialog boxes, entire screen contents, etc., are usually represented as components.
  • React advocates Functional programming and One-way data flow: Given the original interface (or data), if you apply a change, you can deduce another State (interface or data update)
  • Components can divide the UI into independent and reusable components, so that you only need to focus on building each individual component. Components are conceptually like functions that accept arbitrary input values ​​(called "props") and return a React element that needs to be displayed on the page.
    1. Read-only nature of Props
  • Whether a component is declared using a function or class, it must not 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 HTML tags. You cannot use this.props to modify props directly, because props are read-only, and props are used to transfer data and configuration throughout the component tree. To access props in the current component, use this.props.

- props are the setting parameters of a component and can be selectively set in the parent control. The parent component assigns values ​​to the props of the child control, and the values ​​of the props cannot be changed. A child control itself cannot change its own props.

- state: When a component mounts, the state will be used if it is set with a default value, and the state may be changed at any time. A child control can manage its own state, but it should be noted that it cannot manage the state of its child controls. So it can be considered that state is private to the child control itself.

- Each component has its own state. The difference between state and props is that the former (state) only exists inside the component. You can only call this.setState from the current component to modify the state value (it cannot be modified directly) this.state!).

- Props is a data stream passed from a parent component to a child component, and can be continuously passed to descendant components. However, state represents the internal state of the subcomponent itself. Semantically speaking, changing the state of a component may result in changes to the DOM structure or re-rendering. Props are parameters passed by the parent component, so they 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 whether the state changes or the props passed by the parent component change, the render method may be executed.

- Generally, we update sub-components by changing the state value and updating the props value of the new sub-component to achieve the update.

2.1.1 Communication between components

1. Communication between parent and child components

  • Communication between parent and child props attribute is passed
  • Between the child and the parent, the parent component defines events. When the child component triggers an event in the parent component, it communicates by changing the data in the parent component in the form of actual parameters

That is:
- * The parent component updates the component status—–props—–> Child component updates
- * The child component updates the parent component state—–The parent component needs to pass the callback function—–> Child Component call trigger

2. Communication between non-parent-child components. Non-parent-child components that are not deeply nested can be implemented as common parent components and trigger event functions by passing formal parameters

Brothers Component:

(1) According to React's one-way data flow method, we need to use the parent component to transfer and change the props of the sibling components through the parent component callback function.
- In fact, this implementation method is similar to the way in which the child component updates the state of the parent component.

(2) When the component level is very deep, here, React officially provides us with a context method that allows sub-components to directly access ancestor data or functions without having to go from ancestor components layer by layer. Pass data to child components.

2.1.2 Component life cycle

construtor() //创建组件
componentWillMount() //组件挂载之前
componentDidMount() // 组件挂载之后
componentWillReceiveProps() // 父组件发生render的时候子组件调用该函数
shouldComponentUpdate() // 组件挂载之后每次调用setState后都会调用该函数判断是否需要重新渲染组件,默认返回true
componentDidUpdate() // 更新
render() //渲染,react中的核心函数
componentWillUnmount() //组件被卸载的时候调用,一般在componentDidMount注册的事件需要在这里删除

2.2 vue中的组件和数据流

2.2.1 组件化应用构建

  • 组件系统是 Vue 的另一个重要概念,因为它是一种抽象,允许我们使用小型、独立和通常可复用的组件构建大型应用。
  • 在 Vue 里,一个组件本质上是一个拥有预定义选项的一个 Vue 实例
  • 在一个大型应用中,有必要将整个应用程序划分为组件,以使开发可管理。
  • 组件(component)是 Vue 最强大的功能之一。组件可以帮助你扩展基本的 HTML 元素,以封装可重用代码。在较高层面上,组件是 Vue 编译器附加行为后的自定义元素。在某些情况下,组件也可以是原生 HTML 元素的形式,以特定的 is 特性扩展。
  • 组件中,data必须是一个函数
  • 组件可以扩展 HTML 元素,封装可重用的代码。在较高层面上,组件是自定义元素,Vue.js 的编译器为它添加特殊功能。在有些情况下,组件也可以是原生 HTML 元素的形式,以 is 特性扩展。

2.2.2 响应式

  • 当一个 Vue 实例被创建时,它向 Vue 的响应式系统中加入了其 data 对象中能找到的所有的属性。当这些属性的值发生改变时,视图将会产生“响应”,即匹配更新为新的值。
  • 当这些数据改变时,视图会进行重渲染。值得注意的是只有当实例被创建时 data 中存在的属性是响应式的。

2.2.3 组件的生命周期

  • 每个 Vue 实例在被创建之前都要经过一系列的初始化过程。例如需要设置数据监听、编译模板、挂载实例到 DOM、在数据变化时更新 DOM 等。同时在这个过程中也会运行一些叫做生命周期钩子的函数,给予用户机会在一些特定的场景下添加他们自己的代码。
  • 比如 created 钩子可以用来在一个实例被创建之后执行代码,也有一些其它的钩子,在实例生命周期的不同场景下调用,如 mounted、updated、destroyed。钩子的 this 指向调用它的 Vue 实例。
  • 生命周期图示:
    What is the difference between reactjs and vuejs

2.2.3 组件之间的通信

  • Vue默认的是单向数据流,这是Vue直接提出来说明的,父组件默认可以向子组件传递数据,但是子组件向父组件传递数据就需要额外设置了。
  • Vue 也支持双向绑定,默认为单向绑定,数据从父组件单向传给子组件。在大型应用中使用单向绑定让数据流易于理解。
  • 父子组件之间的数据通信是通过Prop和自定义事件实现的,而非父子组件可以使用订阅/发布模式实现(类似于Angualr中的非父子指令之间的通信),再复杂一点也是建议使用状态管理(vuex)。
  • 在 Vue 中,父子组件之间的关系可以概述为:props 向下,events 向上。父组件通过 props 向下传递数据给子组件,子组件通过 events 发送消息给父组件。

1.父向子

- 每个组件实例都有自己的孤立隔离作用域。也就是说,不能(也不应该)直接在子组件模板中引用父组件数据。要想在子组件模板中引用父组件数据,可以使用 props 将数据向下传递到子组件。 

- 每个 prop 属性,都可以控制是否从父组件的自定义属性中接收数据。子组件需要使用 props 选项显式声明 props,以便它可以从父组件接收到期望的数据。 

- 动态Props,类似于将一个普通属性绑定到一个表达式,我们还可以使用 v-bind 将 props 属性动态地绑定到父组件中的数据。无论父组件何时更新数据,都可以将数据向下流入到子组件中

2.子向父

- 使用自定义事件
- 每个 Vue 实例都接入了一个事件接口(events interface),也就是说,这些 Vue 实例可以做到:
- 使用 on(eventName)监听一个事件−使用emit(eventName) 触发一个事件

3. 非父子组件通信
- 可以使用一个空的 Vue 实例作为一个事件总线中心(central event bus),用emit触发事件,on监听事件

3.状态管理

3.1 react中的状态管理:Flux

  • Redux is the most popular Flux implementation in the React ecosystem. Redux is not actually view layer aware, so it can easily be used with Vue with some simple bindings.
    Create actions
    • Define actions. Event triggering requires a dispatcher to call
    • behaviors, such as add operations, delete operations, and update operations, which are a bunch of functions.
    Create store
    • The store contains the status and logic of the application, which is used to manage different states and logic in the application. It is equivalent to the Model layer
    Create dispatcher
    • In the dispatcher, inject the corresponding method in the store to each action through register
    Call the method in the action in the view layer
    • That's it Various components

What is the difference between reactjs and vuejs

##3.2 State management in vuevuex

    vuex draws on Flux, Redux, and The Elm Architecture. Unlike other patterns, Vuex is a state management library specifically 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 improved development experience.
  • Components are not allowed to directly modify the state belonging to the store instance, but should execute actions to distribute (dispatch) events to notify the store to change. We finally reached the Flux architecture. The advantage of this agreement is that we can record all state changes that occur in the store, and at the same time implement advanced debugging tools that can record changes (mutation), save state snapshots, and historical rollback/time travel.

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

  • Vuex is different from a simple global object in the following two points:

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

    2. You cannot directly change the state in the store. The only way to change the state in the store is to explicitly commit a mutation. This allows us to easily track every state change, allowing us to implement some tools to help us better understand our application.

    3. State

  • Vuex uses a single state tree - yes, one object contains all application-level states. It now exists as a "Single Source of Data (SSOT)". This also means that each application will only contain one store instance. A single state tree allows us to directly locate any specific piece of state and easily obtain a snapshot of the entire current application state during debugging. This also means that each application will only contain one store instance.

  • Get the state value from state. Sometimes we need to derive some state from the state in the store, such as filtering and counting the list.

    1. Mutation


      The only way to change the state in the Vuex store is to submit a mutation. Mutations in Vuex are very similar to events: each mutation has a string event type (type) and a callback function (handler). This callback function is where we actually make the state changes, and it accepts state as the first parameter.
    • You cannot call a mutation handler directly. This option is more like an event registration: "When a mutation of type increment is triggered, call this function." To wake up a mutation handler, you need to call the store.commit method with the corresponding type
    2. Action

    • Action is similar to mutation, except that

    • Action submits a mutation instead of directly changing the state.

    • Action can contain any asynchronous operation.
    • dispatch distribution action
    3. Module

  • Due to the use of a single state tree, all the states of the application will be concentrated into a relatively large object. When an application becomes very complex, store objects have the potential to become quite bloated.
  • Vuex allows us to split the store into modules. Each module has its own state, mutation, action, getter, and even nested sub-modules - divided in the same way from top to bottom

4. Routing

    The routing of the two is very similar, they both use the idea of ​​componentization

4.1 Routing in react

  • 在路由库的问题上,React 选择把问题交给社区维护,因此创建了一个更分散的生态系统。但相对的,React 的生态系统相比 Vue 更加繁荣。
  • react中,需要引入react-router库,
    使用时,路由器Router就是React的一个组件。
  • Router组件本身只是一个容器,真正的路由要通过Route组件定义。
  • Route组件定义了URL路径与组件的对应关系。你可以同时使用多个Route组件。
<Router history={hashHistory}>
  <Route path="/" component={App}/>
  <Route path="/repos" component={Repos}/>
  <Route path="/about" component={About}/>
</Router>

- Link组件用于取代元素,生成一个链接,允许用户点击后跳转到另一个路由。它基本上就是元素的React 版本,可以接收Router的状态。

4.2 vue中的路由

  • Vue 的路由库和状态管理库都是由官方维护支持且与核心库同步更新的。
  • 使用 Vue.js ,我们已经可以通过组合组件来组成应用程序,当你要把 vue-router 添加进来,我们需要做的是,将组件(components)映射到路由(routes),然后告诉 vue-router 在哪里渲染它们。

    HTML中:
<div id="app">
  <h1>Hello App!</h1>
  <p>
    <!-- 使用 router-link 组件来导航. -->
    <!-- 通过传入 `to` 属性指定链接. -->
    <!-- <router-link> 默认会被渲染成一个 `<a>` 标签 -->
    <router-link to="/foo">Go to Foo</router-link>
    <router-link to="/bar">Go to Bar</router-link>
  </p>
  <!-- 路由出口 -->
  <!-- 路由匹配到的组件将渲染在这里 -->
  <router-view></router-view>
</div>

5. 渲染性能对比

  • 在操作界面时,要尽量减少对DOM的操作,Vue 和 React 都使用虚拟DOM来实现,并且两者工作一样好。
  • 尽量减少除DOM操作以外的其他操作。(vue和react的不同)

5.1 react视图渲染

  • React 的渲染建立在 Virtual DOM 上——一种在内存中描述 DOM 树状态的数据结构。当状态发生变化时,React 重新渲染 Virtual DOM,比较计算之后给真实 DOM 打补丁。

  • Virtual DOM 提供了函数式的方法描述视图,它不使用数据观察机制,每次更新都会重新渲染整个应用,因此从定义上保证了视图与数据的同步。它也开辟了 JavaScript 同构应用的可能性。

  • 在超大量数据的首屏渲染速度上,React 有一定优势,因为 Vue 的渲染机制启动时候要做的工作比较多,而且 React 支持服务端渲染。

  • 元素是构成 React 应用的最小单位。元素用来描述你在屏幕上看到的内容,与浏览器的 DOM 元素不同,React 当中的元素事实上是普通的对象,React DOM 可以确保 浏览器 DOM 的数据内容与 React 元素保持一致。

  • 我们用React 开发应用时一般只会定义一个根节点。但如果你是在一个已有的项目当中引入 React 的话,你可能会需要在不同的部分单独定义 React 根节点。我们将 元素传入一个名为 ReactDOM.render() 的方法来将其渲染到页面上,页面上就会显示该元素。

组件渲染

- 当React遇到的元素是用户自定义的组件,它会将JSX属性作为单个对象传递给该组件,这个对象称之为“props”。

5.2 vue视图渲染

  • Vue 通过建立一个虚拟 DOM 对真实 DOM 发生的变化保持追踪。

  • vue渲染的过程如下:

    • new Vue,执行初始化
    • 挂载$mount方法,通过自定义Render方法、template、el等生成Render函数
    • 通过Watcher监听数据的变化
    • 当数据发生变化时,Render函数执行生成VNode对象
    • 通过patch方法,对比新旧VNode对象,通过DOM Diff算法,添加、修改、删除真正的DOM元素

6. 数据更新

6.1 react数据更新

  • React 元素都是immutable 不可变的。当元素被创建之后,你是无法改变其内容或属性的。一个元素就好像是动画里的一帧,它代表应用界面在某一时间点的样子。
  • 根据我们现阶段了解的有关 React 知识,更新界面的唯一办法是创建一个新的元素,然后将它传入 ReactDOM.render() 方法

6.2 vue数据更新

7. 开发模式及规模

7.1 react

7.1.1 开发模式

  • React本身,是严格的view层,MVC模式

7.1.2 规模

  • Vue 提供了Vue-cli 脚手架,能让你非常容易地构建项目,包含了 Webpack,Browserify,甚至 no build system。

7.2 vue

7.2.1 开发模式

  • Vue is a way to implement the MVVM pattern
  • Although it does not fully follow the MVVM model, Vue's design 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 there are still some limitations:
    • It does not allow any configuration when the project is generated, and Vue supports Yeoman-like customization.
    • It only provides a single template for building single-page applications, while Vue provides templates for various purposes.
    • It cannot build projects with user-built templates, and self-built templates are particularly useful for pre-established agreements in enterprise environments.

8. HTML&&CSS

  • In React, everything is JavaScript. Not only HTML can be expressed using JSX, but the current trend is increasingly incorporating CSS into JavaScript for processing. This type of approach has its advantages, but there are also trade-offs that not every developer is comfortable with.

- The whole idea of ​​Vue is to embrace classic web technologies and extend on them.

8.1 react

##8.1.1 JSX

    In React, the rendering functions of all components rely on JSX. JSX is a syntactic sugar for writing JavaScript using XML syntax.
  • JSX, a syntax extension for JavaScript. We recommend using JSX to describe user interfaces in React. JSX may look like a templating language at first glance, but in fact it is implemented entirely inside JavaScript.

  • JSX is used to declare elements in React.

  • JSX itself is also an expression. After compilation, JSX will actually be converted into an ordinary JavaScript object. This means that you can actually use JSX in an if or for statement, assign it to a variable, pass it in as a parameter, or use it as a return value.
  • JSX says that the handwritten rendering function is as follows These advantages:

    • You can use the full functionality of the programming language JavaScript to build your view pages. For example, you can use temporary variables, the flow control that comes with JS, and directly reference the value in the current JS scope, etc.
    • The development tools' support for JSX is relatively advanced compared to other currently available Vue templates (for example, linting, type checking, editor auto-completion).

8.1.2 Component-scoped CSS

    Unless you spread the component over multiple files (e.g. CSS Modules), CSS scope is implemented in React through CSS-in-JS solutions (such as styled-components, glamorous and emotion). This introduces a new component-oriented styling paradigm that is different from the normal CSS writing process. Additionally, while it is supported to extract CSS into a separate stylesheet at build time, the bundle usually requires a runtime program to make these styles take effect. While you can use JavaScript to flexibly handle styles, you also need to weigh the bundle size and runtime overhead.

8.2 vue

8.2.1 Templates template syntax

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

    • For many developers who are used to HTML, templates are easier to read and write than JSX. nature. Of course there is an element of subjective preference here, but if this difference will lead to an improvement in development efficiency, then it has objective value.
    • HTML-based templates make it easier to gradually migrate existing applications to Vue.
    • This 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 Vue templates.
  • Vue.js uses an HTML-based template syntax that allows developers to declaratively bind the DOM to the data of the underlying Vue instance. All Vue.js templates are legal HTML and can be parsed by browsers and HTML parsers that follow the specification.
  • In the underlying implementation, Vue compiles the template into a virtual DOM rendering function. Combined with the response system, Vue can intelligently calculate the minimum cost of re-rendering components and apply it to DOM operations when the application state changes.

8.2.2 Single-file component CSS

    The default method for Vue to set styles is a tag similar to style in a single-file component.
  • Single-file components give you full control over the CSS
    in the same file as part of the component code.
  • The style setting in Vue's single-file component is very flexible. Through vue-loader, you can use any preprocessor, postprocessor, and even deeply integrate CSS Modules - all in

8.3 Summary

  • Looking more abstractly, we can divide components into two categories: one is partially view-based (presentational), and the other is partially logical (logical). We recommend using templates for the former and JSX or render functions for the latter. The proportion of these two types of components will vary depending on the application type, but overall we find that there are far more presentational components than logical components.

9. Usage scenarios

9.1 Select react

9.1 .1 Looking forward to building a large application - choosing React

    #A simple application implemented with both Vue and React may make a developer subconsciously prefer Vue. This is because template-based applications are easier to understand at first glance and are faster to run. But these benefits introduce technical debt that prevents applications from scaling to larger scales. Templates are prone to runtime errors that are difficult to notice, and they are also difficult to test, refactor, and decompose.
  • In contrast, Javascript templates can be organized into components with good decomposition and dry (DRY) code, which is more reusable and testable. Vue also has a component system and rendering functions, but React's rendering system is more configurable and has features such as shallow rendering, which can be used in combination with React's testing tools to make the code more testable and maintainable. good.
    At the same time, React's immutable application state may not be concise enough to write, but it is very meaningful in large applications, because transparency and testability become crucial in large projects.

9.1.2 Looking forward to a framework suitable for both web and native APPs - choose React

    React Native is a framework that uses Javascript to build mobile apps Library for native applications (iOS, Android). It's the same as React.js, except instead of using web components, it uses native components. If you have learned React.js, you can quickly get started with 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 web development and mobile development at the same time, React has prepared a great gift for you.
    Alibaba’s Weex is also a cross-platform UI project. It is currently inspired by Vue and uses many of the same syntax. It also plans to fully integrate Vue in the future. However, the time and details of the integration are still unclear. Because Vue uses HTML templates as a core part of its design, and existing features do not support custom rendering, it is difficult to see that the current cross-platform capabilities of Vue.js can be as powerful as React and React Native.

9.1.3 Expect the largest ecosystem - choose React

    There is no doubt that React is currently the most popular front-end framework. It has over 2.5 million downloads per month on NPM, compared to 225,000 for Vue. Popularity is not just a superficial number, it means more articles, tutorials, and more Stack Overflow answers. It also means more tools and plug-ins that can be used in projects, so that developers are no longer alone.
  • Both frameworks are open source, but React was born at Facebook and is endorsed by Facebook. Both its developers and Facebook promise to continue to maintain React. In contrast, Vue is the work of independent developer You Yuxi. You Yuxi is currently maintaining Vue full-time. There are also some companies funding Vue, but the scale is not comparable to Facebook and Google. But please rest assured that Vue’s team has not become a disadvantage because of its small size and independence. Vue has a fixed release cycle. Even more commendable is that Vue has only 54 open issues and 3456 closed issues on Github. As a In comparison, React has as many as 530 open issues and 3447 closed issues.

9.2 Select vue

##9.2.1 Looking forward to template building application - select Vue

The default option for Vue applications is to place markup in the HTML file. Data binding expressions use the mustache syntax similar to Angular, and directives (special HTML attributes) are used to add functionality to the template.
    In contrast, React applications do not use templates and require developers to create the DOM in JavaScript with the help of JSX.

  • Templates are easier to understand for new developers coming from standard web development methods. But some senior developers also like templates, because templates can better separate layout and functionality, and can also use template engines such as Pug.
  • But the cost of using templates is that you have to learn all HTML extension syntax, while the rendering function only requires standard HTML and JavaScript. And compared to templates, rendering functions are easier to debug and test. Of course, you shouldn't miss Vue for this reason, because Vue2.0 provides the option of using templates or rendering functions.

9.2.2 Expect something simple and “just works” – choose Vue

  • A simple Vue project can run directly in the browser without translation, so using Vue can be as easy as using jQuery. Of course this is technically possible with React, but typical React code relies heavily on JSX and ES6 features like classes.
    The simplicity of Vue is reflected even more deeply in programming. Let’s compare how the two frameworks handle application data (that is, state).
  • React determines when to re-render and render content in the DOM by comparing the current state with the previous state, so immutable state is required.
    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 adding a new object to the state, Vue will traverse all the properties in it and convert them into getter and setter methods. Now Vue's response system begins to keep track of the state, and it will automatically change when the content in the state changes. Re-render the DOM. What is commendable is that the operation of changing state in Vue is not only simpler, but its re-rendering system is also faster and more efficient than React's.
  • Vue's response system still has some pitfalls, for example: it cannot detect the addition and deletion of attributes and certain array changes. At this time, you need to use the set method similar to React in the Vue API to solve it.

9.2.3 Expect your application to be as small and fast as possible—choose Vue

  • When the application’s state changes, React and Vue A virtual DOM will be built and synchronized to the real DOM. Both have their own ways of optimizing this process.
    Vue core developers provided a benchmark test, which shows that Vue's rendering system is faster than React's. The test method is to render a list of 10,000 items 100 times, and the results are as shown below. From a practical point of view, this benchmark is only relevant for edge cases and will not be done very often in most applications, so this should not be considered an important comparison point. However, page size is relevant for all projects, and here again Vue leads the way, with its current version only weighing 25.6KB compressed. To achieve the same functionality in React, you need React DOM (37.4KB) and React with Addon library (11.4KB), totaling 44.8KB, which is almost twice the size of Vue. Twice the size does not bring twice the functionality.

10. Server-side rendering (SSR)

  • Client-side rendering route: 1. Request an html -> 2. The server returns an html -> 3. The browser downloads the js/css file in the html -> 4. Waits for the js file to be downloaded -> 5. Waits for the js to be loaded and initialized -> 6. The js code finally works Run, the js code requests data from the backend (ajax/fetch) -> 7. Wait for the backend data to return -> 8. react-dom (client) renders the data into a response page from scratch

  • Server-side rendering route: 1. Request an html -> 2. Server-side request data (intranet request is fast) -> 3. Server-side initial rendering (server-side performance is good, Faster) -> 4. The server returns the page that already has the correct content -> 5. The client requests the js/css file -> 6. Wait for the js file to be downloaded -> 7. Wait for the js to be loaded and initialized. -> 8. react-dom (client) completes the rendering of the remaining part (small content, fast rendering)

10.1 react

  • React’s virtual DOM is the key to its being used for server-side rendering. First, each ReactComponent is rendered in the virtual DOM, and then React uses the virtual DOM to update the changed part of the browser DOM. The virtual DOM acts as an in-memory DOM representation, which provides React with the best performance in non-browser environments such as Node.js. The suck gives you the possibility that React can generate a string from a virtual DoM. Instead of updating the real DOM, this allows us to use the same React Component on the client and server.

  • React provides two functions that can be used for server-side rendering components: React.renderToString and React.render-ToStaticMarkup. You need to be proactive when designing a ReactComponent for server-side rendering and consider the following aspects.

    • Select the optimal rendering function.
    • How to support the asynchronous state of components.
    • How to pass the initialization status of the application to the client.
    • Which life cycle functions can be used for server-side rendering.
    • How to provide homogeneous routing support for applications.
    • Usage of singleton, instance and context.

10.2 vue

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

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

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

2. Server Side Rendering Advantages

- Better SEO since search engine crawlers can directly view the fully rendered page .

- Faster time-to-content, especially for slow network conditions or slow-running devices. There's no need to wait for all JavaScript to finish downloading and executing before displaying server-rendered markup, so your users will see a fully rendered page faster. It generally results in a better user experience, and is critical for applications where time-to-content is directly related to conversion rate.

11. Attached: react concept

1. Divide the UI diagram into component levels

##2. Create a static version with React

    Passing in the data model, rendering the UI but without any interaction. It's best to decouple these processes, because creating a static version requires more coding and less logical thinking, while adding interaction requires more logical thinking than coding.
  • Do not use state when creating static versions.
  • You can build applications top-down or bottom-up. That is, you can start building from the highest level component (i.e. FilterableProductTable) or the lowest level component (ProductRow). In simpler examples, top-down is usually easier, while in larger projects, bottom-up is easier and facilitates writing tests as you build.
  • React's one-way data flow (also called one-way binding) ensures that everything is modular and fast.

3. Define a minimal (but complete) representation of UI state

  • Think 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 piece of data:

      Is it passed from the parent via props? If so, he may not be in state.
    • Is it constant over time? If it is, it's probably not state.
    • Can you calculate it based on any other state or props in the component? If it is, it is not state.

4. Determine where your State should be

  • For each state in your application:

      Determine each component that requires this state to render.
    • Find a public owner component (a component that is hierarchically higher than all other components that require this state)
    • This public owner component or another component with a higher level should own this state.
    • If you don't find a component that can own the state, create a component that just holds the state and add it higher than the public owner component.

5. Add reverse data flow

Summary

To summarize, we found that

The advantages of Vue include:

-Flexible selection of templates and rendering functions

-Simple syntax and project creation
- Faster rendering speed and smaller size

The advantages of React include:

- More suitable for large applications and better testability

- Applicable to both web and native apps
- A larger ecosystem brings more support and tools
- In fact, React and Vue are both very excellent frameworks. are more similar than different, and most of their best features are the same:
- Fast rendering with
Virtual DOM - Lightweight
- Responsive Format and componentization
- Server-side rendering
- Easy to integrate routing tools, packaging tools and state management tools
- Excellent support and community

Related recommendations: "

vue. js tutorial

The above is the detailed content of What is the difference between reactjs and vuejs. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn