• A few days ago, I saw the article @Junking that Vue to React does not completely refer to north. I felt quite interesting. It suddenly occurred to me that I wrote taro+ React + TS before, but now the company happens to use Vue + TS, so this article started.

Vue vs. React

React React React React React React

The same

  1. Both use the Virtual DOM for page rendering
  2. Both provide responsive and componentized view components
  3. Centralized at the UI level, things like routing, state management, and data requests are managed by other libraries

The difference between

  1. Vue is developed as a single file component, that is, the traditional web page HTML, CSS. Javascript is all in one file, while React uses JSX (JSX is a syntax extension of javascript used in react architecture. React’s authors felt that view presentation, data, and logic were naturally coupled, so there was no need to separate them, so React created JSX.

  2. The DIff algorithm is different. Vue DIff uses a bidirectional linked list to update THE DOM while comparing. React mainly stores the DOM that needs to be updated through the DIFF queue, obtains the patch tree, and finally updates the DOM in batches in a unified operation

  3. React Uses the onChange event to update data

  4. Some people think vUE is suitable for small projects, while REACT is suitable for large projects. They have different opinions. However, I think they are both about the same. From React to Vue, I did find that Vue is relatively easy to learn. Options can be written quickly, while React may be a bit more complicated for young people.

The life cycle

Vue2.0

Vue3.0

React

Common life cycles

  1. Vue2.0: Activated, deactivated, created, Mounted, destroyed, and destroyed

  2. Vue3.0: onMounted/onBeforeUnmount/onUnmounted/onRenderTracked/ onRenderTriggered

  3. React: ComponentDidMount/componentDidUpdate/componentWillUnmount/componentWillReceiveProps shouldComponentUpdate (mainly for performance optimization)

  4. React hooks:

    useEffect(() = > {
      console.log('Enter page')
     return () = > {
       console.log('Off page')}}, [])Copy the code

Ahooks: which is a library of hooks from Ali. You can also write them yourself

Components by value

  1. Vue2.0: props/emit/dojo.provide/inject/attrs attrs/attrs/listeners/event bus/vuex, etc

  2. Vue3.0: props/emit/ provide/inject/vuex, etc

Take a chestnut

Child components


<script> 
export default {
    name: 'son'.setup(_, ctx) {
        const handleClick = () = > {
            ctx.emit('onFunc', {msg: 'I am the value passed by the child component'});
        };
        return{ handleClick }; }}; </script>Copy the code

The parent component

<template>
    <testComponents @onFunc="onFunc" />
</template>
<script lang="ts">
import { defineComponent } from "vue";
import testComponents from "@/components/test.vue";
export default defineComponent({
  name:'father'.components: {
    testComponents
  },
  setup() {
    const onFunc = params= > {
      console.log(params.msg); // I am the value passed by the child component
    };
    return{ onFunc }; }});</script>

Copy the code
  1. The React props/props. The function/context/story/mobx/rematch, etc

Components are nested

Vue2.0: slot/v – slot/slot – scope

<template>
    <div id="example">
        <h1>I am the title of the parent component</h1>
        <app-layout>
          <h1 slot="header">(name slot) Here is a page title</h1>
          <p>A paragraph of the main content.</p>
          <p slot="footer">(Named slot) Here's some information</p>
        </app-layout>
    </div>
</template>
<script>
    export default{
        components:{
            'app-layout': {
                template: `
                    <div class="container">
                      <header>
                        <slot name="header"></slot>
                      </header>
                      <main>
                        <slot></slot>
                      </main>
                      <footer>
                        <slot name="footer"></slot>
                      </footer>
                    </div>`,}}}</script>
Copy the code

Vue3.0: slot/v – slot / / # XXX

<template>
  <app-layout>
    <template v-slot:header="slotProps">I am {{slotProps. Data}}</template>
    <template v-slot:default>I'm the default slot</template>
    <template v-slot:footer>I am a footer</template>
    <! -- Dynamic slot name -->
    <template v-slot:[dynamicSlotName] >I am XXX co. LTD. All rights reserved</template>
  </app-layout>
  <p>---------- another way to write it is --------------------------</p>
  <app-layout>
    <template #header="{ data }">I am {{data}}</template>
    <template #default>I'm the default slot</template>
    <template #footer>I am a footer</template>
  </app-layout>
</template>

<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
  name: "app-slot",
  components: {
    "app-layout": {
      template: `
        <div class="container">
          <header >
            <slot name="header" :data='msg' />
          </header>
          <main>
            <slot/>
          </main>
          <footer>
            <slot name="footer" />
          </footer>
          <p>
            <slot name="Copyright" />
          </p>
        </div>`, data() { return { msg: "header" }; } } }, data() { return { dynamicSlotName: "Copyright" }; }});</script>

Copy the code

React


import React from 'react'

const Main = (props) = > {
  return(
    <div>
      <header>{props.header}</header>
      <main>{props.children}</main>
      <footer>{props.footer}</footer>
    </div>)}const Layout = () = > {
  const Header = <div>header</div>
  const Footer = <div>footer</div>
  return(
    <div className='main'>
      <Main 
        header={ Header }
        footer={ Footer }
        >
        <div> main </div>
      </Main>
    </div>)}export default Layout;

Copy the code

Assembly portal

Vue2.0: Currently not supported, but plugins are available

The plug-in is here in portal-vue

Vue3.0: Built-in transmission method

The address Teleport is attached

app.component('modal-button', {
  template: `  
       
        
       `.data() {
    return { 
      modalOpen: false}}})Copy the code

React: createPortal

<html>
  <body>
    <div id="app-root"></div>
    <div id="modal-root"></div>
  </body>
</html>
Copy the code
const appRoot = document.getElementById('app-root');
const modalRoot = document.getElementById('modal-root');

class Modal extends React.Component {
  constructor(props) {
    super(props);
    this.el = document.createElement('div');
  }

  componentDidMount() {
    modalRoot.appendChild(this.el);
  }

  componentWillUnmount() {
    modalRoot.removeChild(this.el);
  }

  render() {
    return ReactDOM.createPortal(
      this.props.children,
      this.el ); }}class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {clicks: 0};
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(state= > ({
      clicks: state.clicks + 1
    }));
  }

  render() {
    return (
      <div onClick={this.handleClick}>
        <p>Number of clicks: {this.state.clicks}</p>
        <p>
          Open up the browser DevTools
          to observe that the button
          is not a child of the div
          with the onClick handler.
        </p>
        <Modal>
          <Child />
        </Modal>
      </div>); }}function Child() {
  return (
    <div className="modal">
      <button>Click</button>
    </div>
  );
}

ReactDOM.render(<Parent />, appRoot);
Copy the code

Functional reuse in components:

vue2.0

Generally, minxins are mixed in


// minix.js
export default {
    data () {
        return {
            name: 'minix'.minixName: 'minixObj'.flag: false}},mounted() {
        console.log('minixMounted');
    },
    methods: {
        speak() {
            console.log('this is minix');
        },
        getData() {
            return '100'; }}}// todo.vue
import myMinxin from './minix';
export default {
    data () {
        return {
            name: 'todo'.lists: [1.2.3.4]}},mounted() {
        console.log('todoMounted');
    },
    minixs: [myMinxin], // Declare minix to mix in todo.vue
    methods: {
        speak () {
            console.log('this is todo');
        },
        submit() {
            console.log('submit'); }}},Copy the code

Vue3.0 draws on the ideas of react hooks and is written in a similar way


import { ref, Ref, watch } from "vue";

export interface CountRange {
    min: number;
    max: number;
}

interface Result {
    current: Ref<number>;
    minus: (num: number) = > void;
    plus: (num: number) = > void;
    set: (num: number) = > void;
    reset: () = > void;
}

export function useCount(init: number, range: CountRange) :Result {
    const current = ref(init);

    const minus = (num: number) = > {
        current.value -= num;
    };
    const plus = (num: number) = > {
        current.value += num;
    };
    const set = (num: number) = > {
        current.value = num;
    };
    const reset = () = > {
        current.value = init;
    };

    watch(current, (newVal: number, oldVal: number) = > {
        if (newVal === oldVal) { return; }
        if (newVal < +range.min) {
            current.value = +range.min;
        } else if(newVal > +range.max) { current.value = +range.max; }});return { current, minus, plus, set, reset };
}

Copy the code

<script lang="ts">
import { defineComponent, reactive, ref } from 'vue';
import { CountRange, useCount } from '@/composition/use-count';

export default defineComponent({
  name: 'Home'.props: {
    title2: String
  },
  data() {
    return {
      title1: 'this is title1'
    };
  },
  setup() {
    const title2 = ref('this is title2');

    const range: CountRange = reactive({
      min: 5.max: 50
    });

    const { current, minus, plus, set, reset } = useCount(10, range);

    return{ title2, range, current, minus, plus, set, reset, }; }}); </script>Copy the code

React: hooks


import React, { useState, useCallback, useEffect } from "react";

export const useWinSize = () = > {
  const [size, setSize] = useState({
    width: document.documentElement.clientWidth,
    height: document.documentElement.clientHeight
  });

  const changeSize = useCallback(() = > {
    // useCallback caches the function
    setSize({
      width: document.documentElement.clientWidth,
      height: document.documentElement.clientHeight }); } []); useEffect(() = > {
   window.addEventListener("resize", changeSize);
    return () = > {
      window.removeEventListener("resize", changeSize); }; } []);returnsize; }; -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - use -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --import React from "react";
import { useWinSize } from ".. /hooks";
export default() = > {const size = useWinSize();
  return (
    <div>Page size: '{size.width}*{size.height}</div>
  );
};
Copy the code

Status Global management

Vue2.0 / VUe3.0: both use VUex

React: redux/mobx/Recoil/XState/flux

  1. For traditional large complex React applications, Redux is recommended for state management.

  2. Mobx is a good option for small to medium complexity React applications. Mobx provides a similar distributed state management mechanism, which is simpler and easier to use, but not as convenient as Redux in terms of overall state management when complexity is high.

  3. If you want to embrace the future, you can simply use the full solution based on React Hooks.

  4. Other libraries are not available, see the documentation for details.

  5. React has a lot of advanced ways to write react.

About feeling

In the past few years since I entered the industry, I do feel that the speed of front-end changes is too fast, from JQery to Vue/React/Angluar. However, I personally feel that no matter which framework is used, it is almost the same. As long as the basic knowledge is firmly laid down, no matter what framework is used, it is easy to use.

As I grow older, I feel more and more that my body is not as good as it used to be. It’s pretty bald. Said. Anyway, or hope that you see the officer usually also want to strengthen physical exercise! As the old saying goes, health is the capital of revolution. Only with a good body can we have a better future. There are ways to make hair more can comment, after all, no one wants to go bald, ha ha ha.

About learning

Everyone says that Vue is easier than React. If it is only at the level of being able to use react, I think it is almost the same. It may be a bit more complicated for some beginners to write React. If you’re used to react, you’ll probably feel more comfortable writing react.

Learning method: for some entry-level white, if the document may not understand some terms, you can first look at the video, like foreign YouTube video, B station, some technical blogs, and then is to do not understand the question more knock, more ask. Take more notes, slowly do more projects, naturally are not a problem.

  1. Vue3.0 website

  2. 30 minutes to quickly master vue3

  3. The react website

  4. Learn React Hooks in 30 minutes

The last