preface

Vue and React are among the most popular and ecological front-end frameworks available. The framework itself is not superior or inferior, only applicable, and the most important goal is to choose the technology that fits our business scenario and team base.

The blogger used Vue framework a year ago and transferred to React framework in the past six months. She has some basic understanding of BOTH Vue and React. Here we take a closer look at Vue and React and discuss their differences. (If you are using Vue and are interested in react, see the difference between the two and vice versa)

Overall content overview:

Due to the long content, I will be divided into the first, middle and the next three parts to discuss with you together (welcome to discuss and communicate with you under the article if you have different opinions, thank you for your support).

1. The background

vue

Former Google engineer Yu Yuxi created the framework in 2014. 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.

react

Unlike Vue, the React library was created by Facebook. It was originally created for Facebook AD traffic management. At the time, Facebook was having maintenance and coding problems. It is known for its ability to dynamically create and interact with UIs.

2. Core ideas

Vue and React both promote the concept of component development, but they differ greatly in their core design ideas.

vue

The whole idea of VUE is still to embrace the classic HTML (structure)+ CSS (presentation)+ JS (behavior) format. Vue encourages developers to use templates and provides instructions for developers to use (V-if, V-show, V-for, etc.). As a result, developing a VUE application feels like writing a classic Web application (structure, presentation, behavior separation). On the other hand, in terms of component data, VUe2.0 makes a more detailed monitoring of data through Object.defineProperty to achieve precise component-level updates.

react

React is a functional concept as a whole. The components use JSX syntax, all in JS, and integrate HTML and CSS into javaScript. JSX syntax is relatively more flexible, and I was not comfortable with it at first. When a component calls setState or props, the internal render of the component is rerendered, and the child components are also rerendered. ShouldComponentUpdate or PureComponent can be used to avoid unnecessary re-rendering (not as well as Vue in my opinion).

3. Component form

vue

Vue component definition is represented by xx.vue file. Vue component combines HTML, CSS and JS together, and template part uses data {{}}, in the following form:

/ / template (HTML) < template > < div > {{name}} < / div > < / template > / / data management (js) < script >export default {
  name: 'NewComponent'.data() {
    return {
      name: 'xx'}}} < / script > / / style sheet (CSS) < style scoped > < / style >Copy the code

Component use:

<new-component name="xx" />
Copy the code

react

It is recommended to use JSX or JS files to represent components. React supports class components and function components. React uses {} to wrap variables.

Note: Component names must begin with a capital letter. React will treat components that begin with a lowercase letter as native DOM tags. For example,

represents an HTML div tag, while
represents a component and needs to use Welcome in scope.

(1) Class components

import React from 'react';

class NewComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'xx'
    };
  }
  render() { rerurn(<div>{name}</div>); }}export default NewComponent;
Copy the code

(2) Function component

Hooks give the function component the ability to manage state.

import React, { useState } from 'react';

function NewComponent() {
  const [name, setName] = useState(' ');
  return (<div>{name}</div>);
}

export default NewComponent;
Copy the code

4. Data Management (props, Data vs State)

Component data management usually consists of two parts, the data props from the parent component and the data itself.

In both vue and React, props flow one-way data. Updates to the parent prop flow down to the child components, but not the other way around. A prop can be an array or an object that receives data from the parent component.

vue

props

In vue, props can pass static or dynamic props. Static props generally pass strings.

<blog-post title="My journey with Vue"></blog-post>
Copy the code

Static prop passing Boolean values true can be written like this, while passing false still requires dynamic prop passing.

<blog-post disabled></blog-post>
Copy the code

Dynamic assignment uses V-bind, which can be abbreviated as:.

<blog-post v-bind:title="tile"></blog-post> // short form <blog-post :title="tile"></blog-post>
Copy the code

Dynamic prop is commonly used to pass objects, arrays, booleans (false values, true values can be passed directly to properties), etc.

<blog-post :title="post.title + ' by ' + post.author.name"></blog-post>
Copy the code

data

Vue uses data to manage component data. Vue recursively converts data’s properties into getters/setters so that data’s properties can respond to data changes. Objects must be pure objects (with zero or more key/value pairs). Once observed, there is no need to add reactive properties to the data object again. Therefore, it is recommended that all root-level reactive attributes be declared before instance creation.

When a component is defined, data must be declared as a function that returns an initial data object.

export default {
  name: 'NewComponent'.data() {
    return {
      name: 'xxx',
      age: 12
    }
  }
}
Copy the code

When you need to modify data within a component, you can modify it directly through the VUE instance:

  methods: {
    changeName() {
      this.name = 'new Name'; }}Copy the code

react

props

React props, like Vue, can pass static or dynamic props. Static props generally pass strings.

Both the function component and the class component can use props. The function component uses the props argument to get the props passed down from the parent component.

Function component props:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

const element = <Welcome name="Sara"/ >;Copy the code

The class component uses this. Props to obtain component props:

class Welcome extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    const { name } = this.props;
    return<div>{name}</div>; }}Copy the code

Dynamic props:

<Welcome name={name} />
Copy the code

state

React uses state to manage data in components. Hooks enable function components to manage state as well.

The class component state

It is important that a class component define the state of the data within the component in its constructor. Modifying the data must be done through setState, not directly.

The class component uses state:

class Welcome extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'xx'
    };
    this.changeName = this.changeName.bind(this);
  }

  changeName() {
    this.setState({
      name: 'new name'
    });
  }

  render() {
    const { name } = this.state;
    return<div onClick={this.changeName}>{name}</div>; }}Copy the code

There are two comments about the setState of the class:

  • 1. SetState updates are asynchronous, but are synchronous in setTimeout and native events.
  • SetState updates part of the component data. React automatically merges the data.

When you need to use the previous state value, you can have setState() accept a function instead of an object. This function uses a state as the first parameter and props as the second parameter when the update was applied:

this.setState((state, props) => ({
  counter: state.counter + props.increment
}));
Copy the code
The function component useState

Before React 16.0, function components were pure render components. Hooks gave function components the ability to manage state.

UseState returns a state and a function to update the state. If the new state needs to be computed using the previous state, you can pass the function to setState. This function takes the previous state and returns an updated value.

import React, { useState } from 'react';

function Counter({initialCount}) {
  const [count, setCount] = useState(initialCount);
  return (
    <>
      Count: {count}
      <button onClick={() => setCount(initialCount)}>Reset</button>
      <button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
      <button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
    </>
  );
}
Copy the code

There are three points about setState:

  • 1. Unlike the setState method in the Class component, useState does not automatically merge updated objects.
  • 2. You can only call a Hook in the outermost layer of a function. Do not call in loops, conditional judgments, or subfunctions.
  • 3. You can only call a hook in the React function component or custom hook. Do not call it from another JavaScript function.

5. Component data interaction

Component data interaction refers to the transfer of data between parent, sibling, and cross-tier components. Sibling components can pass data to each other via the event bus or through the parent component, which I won’t go into detail here.

5.1. Parent-child component data Interaction (props+ custom events vs props+ callbacks)

For parent-child component data interaction, VUE uses prop+ custom events, and React uses props+ callbacks.

vue

In vUE, the parent component passes data to the child component via props. The child component fires a custom event using $emit. The parent component listens for the custom event of the child component to get data from the child component.

The child component uses $emit to pass the custom event myEvent:

<template>
  <div @click="changeName">{{name}}</div>
</template>

<script>
export default {
  name: 'NewComponent'.data() {
    return {
      name: 'xxx',
      age: 12
    }
  },
  methods: {
    changeName() {
      this.name = 'new Name';
      this.$emit('myEvent', this.name);
    }
  }
}
</script>
Copy the code

The parent component listens for custom events using @myevent. The callback argument is the data returned by the child component:

<template>
  <div>
    <new-component @myEvent="getName"></new-component>
  </div>
</template>

<script>
import NewComponent from './NewComponent';

export default {
  components: {
    NewComponent
  },
  data() {
    return {}
  },
  methods: {
    getName(name) {
      console.log(name)
    }
  }
}
</script>
Copy the code

react

In React, the parent component uses the props to pass data and the callback function to its children. The children use the callback function to return data. The parent component uses the callback function to get data from the children.

The child component receives callback events passed by the parent component via props:

import React, { useState } from 'react';

function Children(props) {
  const { myEvent } = props;
  const [name, setName] = useState('xxx');

  const changeName = () => {
    setName('new name');
    myEvent('new name');
  };
  return <div onClick={changeName}>{name}</div>;
}
Copy the code

The parent component gets arguments passed by the child component via a callback event:

function Parent() {
  const changeName = name => {
    console.log(name);
  };
  return <Children myEvent={changeName}></Children>;
}
Copy the code

5.2. Inter-component data interaction (Provide/Inject vs Context)

Vue and React support cross-component data transfer. Vue uses provide/Inject while React uses Context.

vue

Vue provides/inject a dependency from the ancestor component to all descendants, no matter how deep the component hierarchy is, and remains in effect as long as the upstream/downstream relationship is established.

The ancestor component defines the provide option, which should be an object or a function that returns an object.

<template>
  <div>
    <new-component @myEvent="getName"></new-component>
  </div>
</template>

<script>
import NewComponent from './NewComponent';

exportDefault {provide: {// define the provide option message:'This is a big news'
  },
  components: {
    NewComponent
  },
  data() {
    return {}
  },
  methods: {
    getName(name) {
      console.log(name)
    }
  }
}
</script>
Copy the code

The child component gets the provide option value of its ancestor component through the Inject option, which should be an array of strings or objects.

<template>
  <div>{{message}}</div>
</template>

<script>
export default {
  name: 'Children',
  inject: ['message'].data() {
    return {}
  }
}
</script>
Copy the code

Note: Provide and Inject binding are not responsive. This is intentional. However, if you pass in a listening object, the object’s properties are still responsive.

react

Context provides a way to pass data across the component tree without manually adding props for each layer of components.

Create a Context object in the parent component and pass the value to the consuming component through the context. provider value property.

import React, { useState } from 'react'; Const MyContext = react.createcontext ({theme:'black' });

function Parent() { const changeName = name => { console.log(name); }; // context. provider passes values to the consuming componentreturn (<MyContext.Provider value={{ theme: 'white' }}>
    <Children myEvent={changeName}></Children>;
  </MyContext.Provider>);

}
Copy the code

The consuming component gets the Context in two ways:

(1) The class component uses contextType to get the value of the most recent Context.

class DeepChildren1 extends React.Component {
  constructor(props) {
    super(props);
  }

  static contextType = MyContext;

  render() {
    return<div>{this.context.theme}123</div>; }}Copy the code

(2) Functional components subscribe to changes to the Context via context.consumer.

function DeepChildren(props) {
  return (<MyContext.Consumer>
    {
      (value) => (
        <div>{value.theme}</div>
      )
    }
  </MyContext.Consumer>);
}
Copy the code

Note about Context:

When the Provider’s parent is re-rendered, the consumers component is re-rendered, and there is no way to avoid using the Context.

6. The class and style

There are also big differences between Vue and React in class and style processing.

vue

Vue specifically enhances class and style to pass strings, objects, and arrays.

class

(1) bind string to class:

<div class="hello"></div>
Copy the code

(2) bind object to class:

<div
  class="static"
  :class="{ active: isActive, 'text-danger': hasError }"
></div>
Copy the code

The data is as follows:

data: {
  isActive: true,
  hasError: false
}
Copy the code

The HTML will be rendered as:

<div class="static active"></div>
Copy the code

(3) bind array to class:

<div :class="[activeClass, errorClass]"></div>
Copy the code

The data is as follows:

data: {
  activeClass: 'active',
  errorClass: 'text-danger'
}
Copy the code

The HTML will be rendered as:

<div class="active text-danger"></div>
Copy the code

(4) Classes can also be tied directly to components, which React does not support.

Declare the following components:

Vue.component('my-component', {
  template: '<p class="foo bar">Hi</p>'
})
Copy the code

Add some classes when you use it:

<my-component class="baz boo"></my-component>
Copy the code

The HTML will be rendered as:

<p class="foo bar baz boo">Hi</p>
Copy the code

style

Style is used to bind inline styles, and supports passing objects and arrays. CSS attributes that need to be prefixed by the browser engine, such as Transform, vue.js, will automatically detect and add the corresponding prefixes.

(1) Pass objects, CSS property names can be camelCase or kebab-case delimited (remember to use quotes) to name:

<div :style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
Copy the code

The data is as follows:

data: {
  activeColor: 'red',
  fontSize: 20
}
Copy the code

The HTML will be rendered as:

<div style="color: red; font-size: 20px;"></div>
Copy the code

(2) Pass arrays apply multiple styles to the same element

<div :style="[baseStyles, overridingStyles]"></div>
Copy the code

The data is as follows:

baseStyles: {
  fontSize: '20px',
  color: 'blue'
},
overridingStyles: {
  height: '80px'
}
Copy the code

The HTML will be rendered as:

<div style="font-size: 20px; color: blue; height: 80px;"></div>
Copy the code

react

React uses className to specify the CSS class. React does not specify classes for components.

className

React classnames pass values as string constants or string variables, not arrays or object syntax.

(1) Pass string constants:

function NewComponent() {
  return <div className="container" >This is New Component.</div>;
}
Copy the code

(2) Pass string variable:

function NewComponent() {
  const newClass = 'conrainer'
  return <div className={newClass}>This is New Component.</div>;
}
Copy the code

(3) Pass multiple classes, you can use es6 template string implementation:

function NewComponent() {
  const newClass = 'conrainer'
  return <div className={`${newClass} new-container`}>This is New Component.</div>;
}
Copy the code

When passing array or object syntax, we can introduce the classNames library implementation:

import classNames from 'classnnames';

function NewComponent() {
  const newClass = 'container';
  return <div className={classNames(newClass, 'newContainer', { bar: true},'new-class', { c: true }])}>This is New Component.</div>;
}
Copy the code

The HTML will be rendered as:

<div class="container newContainer bar new-class c">This is New Component.</div>
Copy the code

style

The style attribute is generally not recommended as the primary way to style elements. In most cases, you should use the className attribute to refer to a class defined in an external CSS stylesheet. Style is used in React applications to add dynamically computed styles during rendering.

Style receives an object

const divStyle = {
  color: 'blue',
  backgroundImage: 'url(' + imgUrl + ') '};function HelloWorldComponent() {
  return<div style={divStyle}>Hello World! </div>; }Copy the code

Note: Styles do not auto-complete prefixes. To support older browsers, manually add the corresponding style attributes:

const divStyle = {
  WebkitTransition: 'all', // note the capital 'W' here
  msTransition: 'all' // 'ms' is the only lowercase vendor prefix
};

function ComponentWithTransition() {
  return <div style={divStyle}>This should work cross-browser</div>;
}
Copy the code

7. Life cycle

The life cycle of a component generally consists of four phases: initialization, mount, update, and uninstall. Next, take a look at the life cycle of VUE and REAC respectively.

vue

Vue life cycle diagram:

The VUE lifecycle consists of:

  • The beforeCreate instance component has just been created, the DOM element and data have not been initialized, so we can’t do anything for this cycle.
  • The Created data data is initialized and the method is callable, but the DOM is not rendered. Calling the background interface to get the data can be done at this stage.
  • BeforeMount DOM is not complete, data is initialized, but bidirectional binding of data is still displayed {{}}, virtual DOM structure has been generated.
  • The MOUNTED data and DOM are both mounted, and the value of the data in the last cycle is rendered. This cycle is suitable for performing initialization methods that require manipulation of the DOM.
  • BeforeUpdate The page is triggered when data changes. This parameter is triggered before the update. The data is the same as before the update.
  • Updated page All data changes are triggered after the update is complete. In this case, the data is the updated data.

Note: It is easy to get stuck manipulating data here.

  • BeforeDestroy Executed before component destruction, data and Method can still be accessed during this cycle, and communication between components can be done during this phase when information needs to be published.
  • Destroyed is triggered when the component is destroyed upon leaving the corresponding page of the component. It is used to eliminate side effects (cancel event listening, timer, unnecessary requests, etc.)

react

The React lifecycle is divided into pre-16.0 and post-16.0:

16.0 before

The lifecycle prior to React16.0 is as follows:

(1) Initialization

  • Constructor is the default method for a class component and is used to initialize state or set properties, etc.
class Counter extends React.component{ constructor(props){ super(props); // Declare constructor by calling the super method this.state = {count: 0}; this.color ='red'; }}Copy the code

(2) Mount stage

  • ComponentWillMount () is called before the component is mounted, and only once.
  • Render Render is a lifecycle function that the React component must define to render the DOM. You must return a React element that does not render the component. React itself renders the page DOM from this element.

Do not modify state in render, it will cause an endless loop and get stuck.

  • The componentDidMount() component is called after completion, in which real DOM elements can be retrieved, and is often used to make asynchronous requests to retrieve data.

(3) Update stage

When changing state with setState or the parent component rerender causes props to update, it causes the child component to rerender.

  • ComponentWillReceiveProps nextProps props change and parent component function to render will trigger the life cycle. In this phase, the props parameter can be obtained using nextProps, and the previous props can be accessed using this.props. SetState can be performed during this life cycle.
  • ShouldComponentUpdate (nextProps,nextState) each time setState or parent rerender causes the child to render. ShouldComponentUpdate (nextProps,nextState) NextState and the this.props, this.state of the current component to determine if it needs to be rerendered. Returns true by default, requires rerender, false does not trigger render.

Generally we use this hook to optimize performance and avoid unnecessary rendering of child components.

  • ComponentWillUpdate (nextProps, nextState) Is called before rendering when the component receives new props or state. Use this as an opportunity to perform preparatory updates before they occur. This method is not called for initial rendering.

Note: this.setstate cannot be called in this method

  • ComponentDidUpdate (prevProps, prevState) This method is called after a component is updated. This method is not performed for the first rendering. This is where you can manipulate the DOM when the component is updated.

Note: setState() can be called directly in componentDidUpdate(), but it must be wrapped in a conditional statement, otherwise it will cause an infinite loop.

(4) Unloading stage

  • componentWillUnmount()

    Is called directly before the component is uninstalled and destroyed. Perform necessary cleanup operations in this method, such as clearing timers, canceling network requests, or clearing incomponentDidMount()And so on.

Note: setState() should not be called in componentWillUnmount() because the component will never be re-rendered.

After 16.0

React 16.0 deprecated lifecycle functions:

  • componentWillMount
  • componentWillReceiveProps
  • componentWillUpdate

But react doesn’t remove these three life cycles for backward compatibility, New alias for UNSAFE_ prefix the three functions of UNSAFE_componentWillMount (), UNSAFE_componentWillReceiveProps (), UNSAFE_componentWillUpdate ().

New lifecycle functions:

  • static getDerivedStateFromProps(nextProps, prevState)
  • getSnapshotBeforeUpdate(prevProps, prevState)

The life cycle is as follows:

Conclusion: (1) Initialization stage remains unchanged (2) Mount stage: GetDerivedStateFromProps => Render => componentDidMount (3) getDerivedStateFromProps => shoudeComponentUpdate => Render => getSnapshotBeforeUpdate => componentDidUpdate (4) Uninstall phase remains unchanged

Next, we will focus on getDerivedStateFromProps and getSnapshotBeforeUpdate.

Static getDerivedStateFromProps(props, state)

GetDerivedStateFromProps is called before the Render method is called, and is called both during the initial mount and during subsequent updates. It should return an object to update state, and if null is returned, nothing is updated.

This method is applicable when the value of state is dependent on props at all times.

The following is an example:

class ScrollingList extends React.Component {
  constructor(props) {
    super(props);
  }
  static getDerivedStateFromProps(nextProps, prevState) {
    if(nextProps.type ! == prevState.type) {return {
            type: nextProps.type,
        };
    }
    return null;
  }
  render() {
    return (
      <div>{/* ...contents... */}</div>
    );
  }
}
Copy the code

(2) getSnapshotBeforeUpdate(prevProps, prevState)

GetSnapshotBeforeUpdate () 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(). This usage is not common, but it can occur in UI processing, such as chat threads that need to handle scrolling positions in a special way. The value of snapshot should be returned (or NULL).

The following is an example:

class ScrollingList extends React.Component { constructor(props) { super(props); this.listRef = React.createRef(); } getSnapshotBeforeUpdate(prevProps, prevState) {// Do we add new items to the list? // Capture the scroll position so we can adjust the scroll position later.if (prevProps.list.length < this.props.list.length) {
      const list = this.listRef.current;
      return list.scrollHeight - list.scrollTop;
    }
    returnnull; } componentDidUpdate(prevProps, prevState, snapshot) { // Adjust the scroll position so that these new items do not push the old items out of the view. // (where snapshot is the return value of getSnapshotBeforeUpdate)if (snapshot !== null) {
      const list = this.listRef.current;
      list.scrollTop = list.scrollHeight - snapshot;
    }
  }

  render() {
    return (
      <div ref={this.listRef}>{/* ...contents... */}</div>
    );
  }
}
Copy the code

8. Event handling (@click vs onClick)

Vue and React are also different in how they handle events.

vue

The V-ON directive is used in VUE to listen for DOM events and run some JavaScript code when triggered. Typically, v-ON is used to receive a method name that needs to be called.

(1) Directly bind the method without passing any parameters. The callback function parameter is the browser event object.

Example:

<div  @click="greet">Greet</div>
Copy the code

Method:

methods: { greet(event) { console.log(event); }}Copy the code

(2) Call methods inline

Example:

<div  @click="greet('hello')">Greet</div>
Copy the code

method:

methods: { greet(message) { this.message = message; }}Copy the code

Sometimes you also need to access native DOM events in a method, and you can pass $event explicitly into a method.

<div  @click="greet('hello', $event)">Greet</div>
Copy the code

method:

methods: { greet(message, event) { this.message = message; }}Copy the code

(3) Event modifier and key modifier

Vue.js adds event modifiers and keypress modifiers to events. (I think this is one of the things Vue does well, as it allows users to focus more on the data logic without having to deal with the details of DOM events.)

ⅰ. Event modifier

Calling event.preventDefault() or event.stopPropagation() in the event handler is a very common requirement. To solve this problem, vue.js provides event modifiers for V-Ons, which are represented by an instruction suffix beginning with a dot.

  • . Stop: Prevents the event from spreading
  • . Prevent: prevents the default behavior of events
  • .capture: Use event capture mode when adding event listeners
  • .self: The event handler is fired when the current element fires
  • .once: The event is triggered only once
  • Passive: tells the browser that you do not want to block the event’s default behavior, and cannot be used with.prevent.

Example:

<! <a V-on :click.stop="doThis"></a> <! <form V-on :submit. Prevent ="onSubmit"></form> <! <a V-on :click.stop.prevent="doThat"></a> <! <form V-on :submit. Prevent ></form> <! -- Use event capture mode when adding event listeners --> <! <div V-on :click.capture= <div V-on :click.capture= <div v-on:click.capture="doThis">... </div> <! Trigger handler only if event.target is the current element itself --> <! <div v-on:click.self= <div v-on:click.self="doThat">... </div> <! <a V-on :click.once= <a v-on:click.once="doThis"></a> <! The default behavior of the scroll event (that is, the scroll behavior) will be triggered immediately --> <! Instead of waiting for 'onScroll' to finish --> <! -- This includes' event.preventdefault () '-- <div V-on :scroll.passive="onScroll">... </div>Copy the code

ⅱ. Key modifier

When listening for keyboard events, we often need to check for detailed keystrokes. Vue allows you to add key modifiers for V-Ons when listening for keyboard events. You can directly convert any valid keyname exposed by keyboardevent. key to kebab-case as a modifier.

Vue provides aliases for most commonly used keycodes

  • .enter
  • .tab
  • .delete (capture the delete and backspace keys)
  • .esc
  • .space
  • .up
  • .down
  • .left
  • .right

Using the keyCode feature is also allowed:

<input v-on:keyup.13="submit">
Copy the code

The following modifiers can be used to implement a listener that triggers mouse or keyboard events only when the corresponding key is pressed.

  • .ctrl
  • .alt
  • .shift
  • .meta

The exact modifier allows you to control events triggered by the exact combination of system modifiers.

<! -- triggered only when Ctrl is pressed --> < [email protected]. exact="onCtrlClick">A</button>
Copy the code

These modifiers restrict the handler function to respond only to a specific mouse button.

  • .left
  • .right
  • .middle

Benefits of V-ON event handling: 1. You can easily locate the corresponding method in JavaScript code by glancing at an HTML template. 2. Because you don’t have to manually bind events in JavaScript, your ViewModel code can be very logical and completely decoupled from DOM, making it easier to test. 3. When a ViewModel is destroyed, all event handlers are deleted automatically. You don’t have to worry about cleaning them.

react

The React element’s event handling is similar to the DOM element’s, but there are a few syntactic differences:

  • React events are named in a camelCase rather than pure lowercase.
  • To use JSX syntax you need to pass in a function as an event handler, not a string.

(1) The event handler does not pass parameters

To use the callback function in a class component, either explicitly bind this or use the arrow function.

When no arguments are passed, the default argument is E, which is a synthesized event. React defines these composite events according to the W3C specification, so you don’t need to worry about cross-browser compatibility.

In React you can’t prevent the default behavior by returning false, you must explicitly use preventDefault.

Show bind this:

class NewComponent extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); HandleClick (e) {e.preventDefault(); console.log(e.target); }render() {
    return<div onClick={this.handleClick}>Click me</div>; }}Copy the code

Arrow function:

class NewComponent extends React.Component {
  constructor(props) {
    super(props);
  }

  handleClick = (e) => {
    e.preventDefault();
    console.log(e.target);
  };

  render() {
    return<div onClick={this.handleClick}>Click me</div>; }}Copy the code

(2) Event handlers pass parameters

Normally we pass extra arguments to event handlers. There are two ways to pass arguments to event handlers:

The arrow function passes parameters in the way that the event object E must be explicitly passed.

class NewComponent extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(e, message) {
    e.preventDefault();
    console.log(message);
  };

  render() {
    return <div onClick={(e) => this.handleClick(e, 'hello')}>Click me</div>; }}Copy the code

Pass e as the second parameter through bind, and the event object and more parameters will be passed implicitly.

class NewComponent extends React.Component { constructor(props) { super(props); } handleClick(message, e) {// e as the second argument e.preventdefault (); console.log(message); };render() {
    return <div onClick={this.handleClick.bind(this, 'hello')}>Click me</div>; }}Copy the code

conclusion

The above is the comparison between React and Vue and the first part of the blogger’s personal thinking. If you think there is something to gain, you can follow it and give a thumbs-up. The code word is not easy, thanks a lot.