affinity

Note: The version numbers used in this article’s examples are in parentheses

Introduction to the

  • vue

Vue is a set of progressive frameworks for building user interfaces. Unlike other large frameworks, Vue is designed to be applied layer by layer from the bottom up. Vue’s core library focuses only on the view layer, making it easy to get started and integrate with third-party libraries or existing projects. On the other hand, when combined with modern toolchains and various supporting libraries, Vue is perfectly capable of providing drivers for complex, single-page applications.

  • react

React is a declarative, efficient, and flexible JavaScript library for building user interfaces. React allows you to combine short, independent pieces of code called “components” into complex UI interfaces.

The life cycle

  • vue

  • react

V16.3 introduces two new lifecycle functions:

  1. Static getDerivedStateFromProps(props, state), called before the Render method when the component is created and updated, should either return an object to update the state or null to not update anything.
  2. GetSnapshotBeforeUpdate (prevProps, prevState) is called before the last render output (submitted to the DOM node). It enables the component to capture some information (for example, scroll position) from the DOM before changes are made. Any return value for this life cycle is passed as an argument to componentDidUpdate().

Three life cycles that might be deprecated are now used with the prefix “UNSAFE_”

  1. componentWillMount
  2. componentWillReceiveProps
  3. componentWillUpdate

Replacing several deprecated lifecycle functions with a static function getDerivedStateFromProps forces developers to perform only side-effect actions before Render, and the actions they can do are limited to deciding on new states based on props and state

responsive

  1. Data -> View

Vue can modify data directly. You can also block the response with object.freeze ()

React needs to be modified with setState.

Vue more concise

Principle:

  • Vue:

Object. DefineProperty is used to recursively convert data’s property into getter/setter during initialization. Dependencies are collected when data is acquired and dependency updates are notified when data is modified.

Vue is executed asynchronously when updating the DOM. As long as it listens for data changes, Vue opens a queue and buffers all data changes that occur in the same event loop. If the same watcher is triggered more than once, it will only be pushed into the queue once. Then, in the next event loop, “TICK,” Vue refreshes the queue and performs the actual (de-duplicated) work. Vue internally attempts to use native Promise.then, MutationObserver, and setImmediate for asynchronous queues, and setTimeout(fn, 0) instead if the execution environment does not support it. Operations on the updated DOM must be performed in nextTick. Note: Additions and deletions of object attributes and partial changes to arrays cannot be hijacked, requiring specific methods.

  • React:

React setState determines whether to update this.state directly or put it in a queue later based on isBatchingUpdates. IsBatchingUpdates are false by default. SetState will synchronize this.state. However, there is a function called batchedUpdates that will set isBatchingUpdates to true. When React calls batchedUpdates before the event handler is called, setState controlled by React does not update this.state synchronously.

SetState is asynchronous only in synthesized events and hook functions, synchronous in native events and setTimeout and setInterval. Note: As shown above, the reference type cannot be changed directly; a different reference is needed to trigger the update

  1. View -> Data
  • vue

Provides syntax-sugar V-models and provides modifiers lazy, number, and trim

  • react

Update the corresponding state by setState after binding event processing

Grammar, API

Note: The following code is configured in the project: Webpack5 + babel7

The project structure

Entrance to the js

The root component

Home page

Route vue with vue-router and react with react-router-dom

Global state, vue with vuex, react with redux, react-redux connection

Vue requires a specific VUE-loader

component

Caller (parent component)

A V-Model on a vUE custom component is equivalent to:

<my-input :value="theName" @change="changeTheName"></my-input>

methods: {
    changeTheName(val) {
        this.theName = val
    },
}
Copy the code

Component communication

Other:

  • vue

$listeners + $listeners, new Vue(), vuex

  • react

redux

Props to write

  • vue

Pass variable values using V-bind: or:, event binding or custom events using V-on: or @

<Child name="jeni" :count="count" @change={handleChange} />
Copy the code

Dynamic parameter support

<a v-bind:[attributeName]="url"> ... </a>
Copy the code
  • react
<Child count={3} onChange={handleChange}/>
Copy the code

Obtain the updated data

  • vue
data() { return { count: 0, }; }, methods: { handleClick() { this.count += 3; console.log('count: ', this.count); / / 3}},Copy the code
  • react
const [count, setCount] = useState(0);

const handleClick = () => {
    setCount(count + 3);
    console.log('count: ', count); // 0
}

useEffect(() => {
    console.log('count2: ', count); // 3
}, [count]);
Copy the code

Because setState is asynchronous in react events, it is still old to be obtained synchronously. UseEffect setCount is the latest value, which may not be the latest value. You need to change it to a transfer function that takes the latest count

setCount(c => c + 3);
Copy the code

Vue instruction

  1. conditions
  • vue
<div v-if="theName.length === 0">1</div>
<div v-else-if="theName.length <= 5">2</div>
<div v-else>3</div>
Copy the code
  • react
{theName.length === 0 && <div>1</div>} {theName.length ! == 0 && theName.length <= 5 && <div>2</div>} {theName.length ! == 0 && theName.length > 5 && <div>3</div>}Copy the code

or

{theName.length === 0 ? 
(<div>1</div>) 
: 
(theName.length <= 5 ? (<div>2</div>) : (<div>3</div>))}
Copy the code
  1. traverse
  • vue

When Vue is updating a list of elements rendered using V-for, it defaults to the “update in place” policy. If the order of data items is changed, Vue does not move DOM elements to match the order of data items, but instead updates each element in place and ensures that they are rendered correctly at each index location.

It is recommended that key attributes be provided whenever possible with V-for, as it is a general mechanism for Vue to identify nodes.

<div v-for="(item, index) in users" :key="item.id" class="list-item"> <div> . {{item name}} < / div > < div > age: {{item. Age}} < / div > < / div > < span v - for = "n in 10" > {{n}} < / span >Copy the code
  • react
{users.map((item, index) => (<div key={item.id} className={styles.listItem}> <div> . {item name} < / div > < div > age: {item. Age} < / div > < / div >)}Copy the code

Note to add key, convenient to do diff operation to quickly know whether two nodes are the same node, and ensure the uniqueness of key!

  1. v-show
  • vue
<div v-show=" thename. length > 10"> </div>Copy the code
  • react
<div style={{display: theName.length > 10 ? 'block' : 'none'}}> theName </div>Copy the code
  1. v-html
  • vue
<div V-html ="htmlContent"></div> <div>{{htmlContent}}</div> htmlContent: '<h1> I am H1 </h1>'Copy the code
  • react
<div dangerouslySetInnerHTML={{__html: HtmlContent}} /> <div>{htmlContent}</div> const [htmlContent] = useState('< H1 > I am H1 </h1>')Copy the code
  1. Other built-in instructions
  • v-model
  • v-text
  • v-bind
  • v-on
  • v-cloak
  • v-pre
  • v-once
  1. Custom instruction
  • vue
< INPUT value=" automatic focus when the page is initialized "V-focus /> directives: {focus: {bind: function() {// Only called once, when the directive is first bound to the element. This is where you can perform one-time initialization Settings. }, /** * EL: element to which the directive is bound * vnode: virtual node generated by the Vue compilation */ inserted: Function (el, binding, vnode, oldVnode) {function (el, binding, vnode, oldVnode) {function (el, binding, vnode, oldVnode) {function (el, binding, vnode, oldVnode) {function (el, binding, vnode, oldVnode) {function (el, binding, vnode, oldVnode) { el.focus(); Const {name, // directive name, excluding the v-prefix value, // directive binding oldValue, // directive binding previous value, Available only in Update and componentUpdated hooks: expression, string directive expressions arg, parameter modifiers passed to directives, // an object containing modifiers} = binding; }, update: function() {// called when the component's VNode is updated, but may occur before its child vNodes are updated. // The value of the instruction may or may not have changed. But you can ignore unnecessary template updates by comparing the values before and after the update. }, componentUpdated: function() { }, unbind: function() {// call once, when instruction and element are unbound. }}},Copy the code

The above code is a local directive that can only be used in the current component and can also define global directives

  • react

Analog implementation

<input value=" page initialization autofocus "ref={inputRef} /> const inputRef = useRef(null); UseEffect (() => {// Similar to the inserted inputref.current. Focus (); Return () => {// similar to unbind} in vue directive; } []); UseEffect (() => {// Similar to vue directive componentUpdated});Copy the code

The event

  • vue

Modifiers are supported in templates through the directive V-on: or @binding events

<form v-on:submit.prevent="onSubmit">... </form>Copy the code

Modifiers include Stop, capture, self, once, and passive (the default behavior of not wanting to prevent the event). Key modifiers: Enter, Page-Down, TAB, delete (capture “delete” and “backspace” keys), ESC, Space, up, Down, left, Right and system modifiers: CTRL, Alt, Shift, meta The. Exact modifier allows you to control events triggered by the exact combination of system modifiers.

  • react

In JSX, the binding event with onClick={handleClick} is a SyntheticEvent. There are no modifiers. To prevent default behavior or bubbling and so on is handled in the binding callback function

Is it executed immediately?

  • vue
<div @click="add()"></div>
Copy the code

The add function is not executed once during initialization

  • react
<div onClick={add()}></div>
Copy the code

You do add once at initialization so if you want to pass parameters, you need to rewrite it to

<div onClick={e => {add(e, name)}}></div>
Copy the code

Calculate attribute

  • Vue

Caching based on reactive dependencies. They are reevaluated only when the associated reactive dependencies change.

computed: { theName2() { return this.theName + '2'; }},Copy the code
  • React
const theName2 = useMemo(() => {
    return theName + '2';
}, [theName])
Copy the code

Listen to attribute

  • Vue

When performing asynchronous or expensive operations when data changes

Watch: {theName: function(newValue, oldValue) {if(newValue - oldValue > 8) {alert('theName '); }}},Copy the code
  • React
const theNameRef = useRef(theName); UseEffect (() => {if(thename-thenameref.current > 8) {alert('theName new value is 8'); } theNameRef.current = theName; }, [theName])Copy the code

class

  • vue
<div class="container" :class="{active: isActive}">
Copy the code
  • react
<div className={styles.container}>
Copy the code

style

  • vue
<div style="width: 20px; height: 20px;" >diff2</div> <div :style="{color: textColor}">diff3</div>Copy the code

When V-bind :style uses CSS properties that require a browser engine prefix, such as transform, vue.js will automatically detect and add the corresponding prefix.

  • react
<div style={{width: '20px', height: '20px'}}>diff2</div>
<div style={{color: textColor}}>diff3</div>
Copy the code

Prop validation

Vue: Not only does it provide documentation for your components, it also alerts the user from the browser’s JavaScript console when they encounter the wrong type. React: There is a separate package that needs to be introduced: prop-types

slot

  • vue
// Parent <slot-test> I am slot content </slot-test> // child <template> <div> I am SlotTest. Vue <div> <slot></slot> </div> </template>Copy the code

This is the simplest. There are also named slots, scoped slots

  • react
// Subcomponent <div> I am SlotTest. JSX <div>{props. Children}</div> </div>Copy the code

Dynamic components

  • vue
<component :is="currentComponent"></component>
Copy the code

Applicable scenarios:

  1. The TAB to switch
  2. Some HTML elements, such as
      , < OL >,

    • ,
    • , and < SELECT >, have strict restrictions on which elements can appear inside them. Some elements, such as

      , and
  • react
const components = [Parent, SlotTest];

const CurrentComponent = components[0];

<CurrentComponent />
Copy the code

Asynchronous components

  • vue

Route Configuration

{ path: '/list', component: () => import(/* webpackChunkName: "list" */ '.. /pages/list'), }, { path: '/diff', component: r => require(['../pages/diff'], r), },Copy the code
  • react
{ path: '/list', component: lazy(() => import('.. /pages/list')),}, // Must make a layer out of components <Suspense fallback="<div>... </div>">Copy the code

Component caching

  • vue

<keep-alive> component instances can be cached when they are first created

  • react

There is no

Mixed with

Mixins React is mostly deprecated and is recommended to use HOC (high-level components) or Render Props

The plug-in

  • vue

Plug-ins are usually used to add global functionality to a Vue. There are no hard and fast limits to what a plug-in can do — there are usually:

  1. Add global methods or properties. Such as: the vue – custom – element
  2. Add global resources: directives/filters/transitions, etc. Such as the vue – touch
  3. Add some component options through global blending. Such as the vue – the router
  4. Add Vue instance methods by adding them to Vue. Prototype.
  5. A library that provides its own API and provides one or more of the functions mentioned above. Such as the vue – the router

Use: Vue. Use (plugin name, option) :

MyPlugin.install = function (Vue, options) {... }Copy the code

Vue-router and Vuex are plug-ins

  • react

There is no

The filter

  • vue

Can be used for some common text formatting. Filters can be used in two places: double curly brace interpolation and v-bind expressions (the latter supported as of 2.1.0+). Filters should be added to the end of JavaScript expressions, indicated by the “pipe” symbol

{{ message | filterA | filterB }}
Copy the code

FilterA is called and the result is passed to filterB as an argument. If filterA passes an argument, message will be the first argument

  • react

The method call

Components access each other

  • vue
  1. $root
  2. $parent
  3. $children
  4. $refs
  • react

forwardRef

Single element/component transitions

  • vue
<transition name="fade">
    <p v-if="show">hello</p>
</transition>
Copy the code
  • react

There is no

Template root node

There must be a root node

  • vue

Can only be actual HTML nodes. Version 3 provides virtual nodes

  • react

This can be the virtual node React.Fragment or <></> to reduce unnecessary tags on the page

other

  1. Vue does not support template partial annotations

Vue pit

  1. The cost of accessing TS is high

Large amount of code modification.

  1. Many global things (ue. Extend, UE. Mixin, UE. Prototype) are messy and hard to maintain

Highlight the vue

  1. Keep-alive, multi-component switching is very useful

  2. More developer friendly with built-in optimizations and lots of syntax candy and apis

The react pit

  1. Conditional rendering: Displays the value when the condition is not of Boolean type and the value is converted to Boolean false
const isShow = 0

{isShow && <div>1234567890</div>}
Copy the code

It’s going to say 0

  1. After an asynchronous request is returned, a message may be displayed indicating that the component is uninstalled and cannot setState. Because other state changes may cause the component to be rerendered

  2. A lot of redundant diff overhead that needs to be manually optimized

When the state of a component changes, it rerenders the entire component subtree with that component as the root. To avoid unnecessary rerendering of child components, you need to use PureComponent wherever possible, or manually implement shouldComponentUpdate and use memo wrapped around functional components. You may also need to use immutable data structures to make your components easier to optimize.

The dependencies of vUE components are automatically tracked during rendering, so the system knows exactly which components really need to be rerendered.

  1. The reference type only changes the value, but does not change the reference

Highlight the react

  1. fiber

Fiber is the new coordination engine in React 16. Its main purpose is to enable incremental rendering of the Virtual DOM. In order to solve the problem that the main thread is occupied by JS operation for a long time, the operation is cut into multiple steps and completed in batches. Older React renders recursively, using the JS engine’s own function call stack, which executes until the stack is empty. Fiber implements its own component call stack, which traverses the component tree in a linked list with the flexibility to pause, continue, and drop tasks. This is done using the browser’s requestIdleCallback API.

Window. RequestIdleCallback () will, in turn, calls the function in the browser free period, it can let developers performing background in the main event loop or low priority task, and not to delay trigger, such as animation and user interaction influence but the key event. Functions are generally executed in first-come-first-called order, unless the function reaches its timeout before the browser calls it.

  1. React Native is a mature and widely used technology for developing Native applications

  2. Mixins -> HOC -> Render Props -> hooks

Reference:

Lq782655835. Making. IO/blogs/vue/d… Jishuin.proginn.com/p/763bfbd54… www.html.cn/qa/react/15… www.cnblogs.com/xzsj/p/1351… Blog.csdn.net/huazai96318… Jishuin.proginn.com/p/763bfbd4f…