Turn: zhuanlan.zhihu.com/p/187377658

! [](https://pic3.zhimg.com/80/v2-7e6dc3335b0a103c14a15ae8764cdc0a_720w.jpg)

Common swing questions, views

First of all, I retalk about the common comparison items, views, these parts can be found through some articles or Vue official comparison documents, the main purpose is to help small white to solve the problem of entry swing. If you object, leave Battle in the comments section, but I won’t answer your questions.

Vue or React documentation is richer?

Both extensive documentation (including Chinese document), Vue document, React in Chinese, so don’t worry you are pass the level 4, can’t read the document, this is all have eyes is done ~ of course, if you know some good javascript knowledge is also greatly drop in advance, ES6 grammar better, can learn here with miss ruan, a free ebook. Documentation and continuous progression are not the reason you choose between the two frameworks.

Vue’s words need to remember a variety of instructions, as well as the details of the attribute, inevitably often check the document. React is relatively simple. Just remember: “Functions for props and HTML for export.”

React learning barriers are high?

This is not the reason why you chose the framework. If this is the reason, I think it is because you are lazy and give yourself an excuse. According to my own study and practice summary, both frameworks are very simple. If you have hands, you can do it. If you have brains, it is not necessarily that React is much better than Vue. The corresponding scaffolding is provided to facilitate the use of users:

Vue

npm install -g @vue/cli
vue create my-project
Copy the code

reaction

npx create-react-app my-app
cd my-app
npm start
Copy the code

If you use it foolishly, the infinite div is done.

React for big projects, Vue for small projects

This was a hallmark of the internal discussion of the two frameworks when I was at Huawei. The so-called? This is the essential oil label, no reference. How do you define a project as a large project? More than xx million lines of code? More than XXX backend apis? No matter what project, there is the possibility of “big”, as long as the normal operation, you have to continue to maintain, to complement the needs. The substitution of the framework is more important. I don’t know, but Vue is not suitable for “big” projects. The problem becomes obvious after 50,000 lines of business code. More on this later.

XX big company also uses Vue, we just follow

Many novices will look at what big companies are already using to avoid getting stuck when getting started with a framework, or selecting components, or solutions. Of course, I can drop too. But big companies are probably just ‘early’, ‘experimental’ uses, and these projects don’t really matter to each other, so when the selection fails, the pressure is on the dev engineer to correct it, and you, as well as poo, need to maintain your project.

Take an example of a lectotype error and see how big companies save it.

When I was doing hardware projects in Huawei, I used the schematic software, which was called a spicy chicken, and I always wanted to smash the computer with it. Historical issues, selection of mistake, but a lot of projects, libraries are based on the above, only crustily skin of head, the migration of high cost, poor level of software vendors, but huawei cow force ah, the big change, the software, all sorts of internal database are integrated in the above, the development of auxiliary tools, or can develop very cow force of the product, The board made by the department has been the first in the world for 11 consecutive years.

– If you think you can handle the problem of type selection errors, or if you’re at Huawei, when we say.

Vue template is simple, React JSX has a learning cost

Same as above. Both are easy to learn. Even this is called the cost of learning, and ALL I can say is, “I’m not taking it personally, I’m just saying that everyone here is…” (The Vue template has a number of engineering practice issues, more on that later.)

The performance comparison

Look at this third party benchmark, which is pretty fast. However, we found some differences in practice, large list rendering, large amount of data loading, without further optimization, Vue is significantly slower than React. TaskHub is a site we used to write in Vue, but after moving directly to React, the front-end performance is greatly improved and the user experience is significantly different (data structure, background is the same).

The depth of the contrast

Originally wanted to write a simple, did not expect to write so much in front, ╮ (added) ╰) bang, the following is the highlight, writing practice found in the process of problems, two framework solutions. Create the same APP, compare React and Vue, and actually do it, and get the basics.

The market share of

! [](https://pic3.zhimg.com/80/v2-0c341db280a416c9982fcf8cba3bc766_720w.jpg)

The market is already voting with its feet. At this point, if you just want to know the selection representative, you can go. If you also say that xx big companies use Vue, just follow. It’s fair to say that larger companies are using React more often, and using Vue is more to preserve the technology stack capability and have an option to avoid React licensing events happening again.

  • What happened to the React license agreement?
  • Facebook rejects React patents, but issues still unresolved?

Of course, you also said here, looking at NPM downloads is useless, the actual use should refer to devTool downloads. But… Why is this logo on the bottom of many websites I open?

! [](https://picb.zhimg.com/80/v2-8868dbbab0526ede50f0ca7e18b8d364_720w.jpeg)

The development of ecological

Objectively speaking, as core team members, we realized that we would be more partial to Vue and thought that certain problems would be better solved with Vue. Without this belief, we would not be so busy all day. But after that, we want to be adjusted to describe everything fairly and accurately. Other frameworks also have significant advantages, such as React’s vast ecosystem officially owned by Vue

The ecological difference is obvious, which is officially acknowledged by Vue. Many people migrate to React because of this ecological point, but I don’t really care about it. Vue ecology is not bad, if you use React ecology things, you will think it is awesome, and your core will also be used, which cannot bring much value to your products. Competitiveness or to rely on their own hand code out of the good. Here is a simple:

UI components

Both have a rich and slightly more responsive UI library, but that’s not the key to the selection, it’s not hard to write your own UI library, and it’s easy to occasionally encapsulate native tags. Before the use of Vue when there is no UI library, manually write a function of a more complete UI library, with summary packaging, also about 20,000 lines of code, there is a hand on the line.

Third-party libraries related to dom

Vue and React both have refs that can manipulate the DOM, so it’s not hard to encapsulate it yourself. You can see if there is no other encapsulation, take the doctrine.

  • Vue: Access a child component instance or child element
  • React: Refs and DOM

Mini program (highlight)

Those of you who have experience in small program development know that small program native development is a pain in the ass, usually requiring serial framework encapsulation and code conversion. There are several common frameworks:

  • Taro (React technology stack, recommended)
  • Wepy (Vue technology stack, strongly not recommended)
  • Uni-app (Vue technology stack, available)

These small program development frameworks are based on Vue or React secondary encapsulation, simplify small program development.

Some of vUE’s peripheral libraries are strongly bound to Vue, rather than exist as a separate JS library. Causing the code to be difficult to understand, related bugs, problems also brought into the secondary development framework.

The problems caused by this strong dependency can lead to many problems in future upgrades and migrations. For example, as the official state management scheme recommended by Vue, VUex can only be used on Vue, not camp. Redux state management is used more for factions than for Vue. There are many similar problems, you will find that things around React can be used for Vue, and things around Vue cannot be used for React.

If you don’t think this is a serious problem, when you migrate your Vue code to the wepy framework, you find that Wepy doesn’t support Vuex (buggy), and you can only use Redux for state management. Same problem, if you are using React related technology stack, reaction migration to Taro applet framework is very simple, and can be generated at one time wechat applet, Alipay applet, bytedance applet, etc., high code usage.

The APP ecosystem

I do not have good practical experience in WEEX and RN, and some of the production plans must be carefully considered. It is clear that Rn is more mature than WEEX.

Logical code organization

! [](https://pic3.zhimg.com/80/v2-ec50f81f9ad0db1bbeba741ffc1f7d70_720w.jpg)

Comparison of three Vue component Writing Methods (Js Part)

Object API line 29

import Vue, { PropOptions } from 'vue'

interface User {
  firstName: string
  lastName: number
}

export default Vue.extend({
  name: 'YourComponent',

  props: {
    user: {
      type: Object,
      required: true
    } as PropOptions<User>
  },

  data () {
    return {
      message: 'This is a message'
    }
  },

  computed: {
    fullName (): string {
      return `${this.user.firstName} ${this.user.lastName}`
    }
  }
})
Copy the code

API class 17 rows

import { Vue, Component, Prop } from 'vue-property-decorator' interface User { firstName: string lastName: number } @Component export default class YourComponent extends Vue { @Prop({ type: Object, required: true }) readonly user! : User message: string = 'This is a message' get fullName (): string { return `${this.user.firstName} ${this.user.lastName}` } }Copy the code

Function API line 25

import Vue from 'vue' import { computed, value } from 'vue-function-api' interface User { firstName: string lastName: number } interface YourProps { user? : User } export default Vue.extend({ name: 'YourComponent', setup ({ user }: YourProps) { const fullName = computed(() => `${user.firstName} ${user.lastName}`) const message = value('This is a message') return { fullName, message } } })Copy the code

! [](https://pic1.zhimg.com/80/v2-6d8ffc8f0501520355f82e3a8bc8557a_720w.jpg)

React Component Comparison (Js part)

Class component 34 lines

import React, { Component } from 'react';

interface P {}

interface S {}

class Index extends Component<P, S> {

  constructor(props: Readonly<P>) {
    super(props);
    this.state = {};
  }

  static defaultProps = {};

  componentDidMount() {}

  componentDidUpdate(prevProps: Readonly<P>) {}

  componentWillUnmount() {}

  render() {
    return (
      <div>
      </div>
    );
  }
}

export default Index;
Copy the code

Function component 15 lines

import React, { FC } from "react"; Interface Props {} const Index: FC<Props> = (Props) => {// js code return (<div></div>); }; Index.defaultProps = {}; export default Index;Copy the code

In the JS logic part of which the writing method is not wrong, all need to use the framework specific life cycle hook, Vue class writing is the most concise (3 kinds of contrast), the reaction of the function writing method is the most clear (all the contrast). This part is not the key, how to write is a personal preference.

Internal state management of components

Vue uses data objects (data) while reflection uses state objects (immutable state). The design of the two frameworks is different, and the following problems are solved differently.

  1. How do I modify the data? Vue directly references this data object and modifies it directly. React is modified using the setState method
  2. How does the framework find that data has been modified? Vue uses es5’s new object.defineProperty method to hijake setters and getters for data listening. React, you use setState, it knows something’s changed by this function.
  3. How do I find out that the data has been modified? Vue: Use observers, or calculate properties to discover reactions: componentWillUpdate, componentDidUpdate can listen for changes, or insert a dependent part of a function component
  4. When the frame renders modified data, how do I know it’s rendered? Vue: Render at the appropriate time, you find the reaction by using watcher, or by calculating the properties: after the setState call, re-render at the appropriate time, and call the relevant lifecycle hook

Both don’t have much of a slot in component state management, if anything Vue Watcher wrote a lot of code and a lot of indentation, and the response wasn’t much better.

Vue is much simpler to write, but there are a lot of component states. When you need explicit data update logic, the simple setState ({}, callback) is done. Vue is a bit confusing.

There is nothing deep Watch can’t solve. If there is something, add immediate event related, dom related remember nextTick, setTimeout

(From a senior)

React’s immutable state is transparent and more testable in complex applications.

Compared with the above content, I feel that both of them are OKOK, with sound functions and poor Vue ecology, but they can have enough food and clothing by themselves. Here’s why we’re really getting rid of Vue. Vosuede Buyod said: the same problem, in the language level of the solution is the best solution. The language lifecycle is longer than the framework lifecycle

Template syntax VS JSX

Part of the missing Vue of the single file components, using

Example:

Export function isNickname(value) {return /^[\s\ s]{1,50}$/.test(value); } <template> <div> {{ a }} <button @click="a = isNickname('abc')">Test</button> {{ b }} </div> </template> <script> // eslint-disable-next-line no-unused-vars import {isNickname} from '.. /fn/filter'; export default { name: 'HelloWorld', props: { msg: String }, data: () => { return { a: false, b: 1, c: 1, } }, methods: { isNickname1() { return isNickname('abc'); } } } </script> <style scoped></style>Copy the code

The above code will report an error:

[Vue warn]: Property or method "isNickname" is not defined on the instance but referenced during render
Copy the code

So you can only define methods in methods and then refer to them. The template syntax doesn’t know you have the isNickname function, which is 3 lines more than the simple operation.

The template syntax is not Turing-complete and must be converted to JS code (rendering functions) in the context of the component. There are many similar examples, you will find that your code is strongly bound to Vue, one day Vue core library upgrade, your code also crashed. As the Vue core library is upgraded, the surrounding dependent libraries need to be upgraded as well.

Division of the template

Good code organization separates variables from constant and invariant parts

Vue’s template severely limits this. For example, there is a drag-and-drop menu on the front end, which is growing in functionality, and different menus are displayed for different people (rights management). In Vue, in order to achieve the separation of HTML code (bound in template), you have to create one more component. In React, you can just write:

const menu = <div>abc<div>;
Copy the code

It can be a separate component (a low-overhead function component), or it can be a variable in the current code. It’s a lot more flexible.

The JSX handwriting render function comes with the following advantages

  • Complete JS functionality to build the view page, using temporary variables, js’s own control flow, and direct references to values in the current JS scope
  • Development tools support JSX at a higher level than existing VUE templates (linting, typescript, compiler auto-completion)

JSX can be used for Vue and can be used for React, just like Redux. The language is decompressed from the framework.

“With all the problems with template syntax, Vue also supports JSX.”

I thought you’d say that, but as mentioned above, since I had to use JSX/TSX, Redux, why didn’t I use React?

“Html-based templates make it easier to gradually migrate existing applications to Vue”

It’s not easier. It’s more trouble. First of all, the templates described below do not linting well, type directives, and many bugs cannot be found in time for code migration. Second, a large part of the code migration is JS logic migration (this is more important), migration to VUE, you need to cram subdivision of the original code, into the calculation, mentality, a lot of work and code and vUE strong binding. Finally, wouldn’t it be easy to batch replace the original code class, @click, with a modern editor, with className, onClick?

Typescript, velveteen support

This is especially deadly because Typescript has become a necessity for our front-end development. A lot of errors can be found before.

Vue templates do not support typescript (officially enhanced), and support for typescript is a lot more “hack” than the original framework. It’s hard to write code in Vue. Extend objects with good TS to support Typescript. We’ve used Vue’s class writing (see above). The front end works with the back end to place interfaces, and many undetected errors are found in the template code.

Testability, refactoring

Vue needs to create a.vue file

<template>
  <div>
    {{hello}}
  </div>
</template>

<script>
export default {
  name: 'Test',
  props: {
    hello: String
  },
  created() {
    console.log(this.hello);
  }
}
</script>

<style scoped></style>
Copy the code

React operations are executed in the JSX environment. They are placed in arbitrary positions. React operations are easier to test than templates.

function Test(props: { hello: string }) {
  console.log(props);
  return <div>{props.hello}</div>
}
Copy the code

The difference between Vue and React test costs is obvious. React goes up and down, one function is done, and it’s clear what you’re testing. Type, attribute modification on the line, the editor automation.

Complex state, action management

Overall state management scheme selection is very important, after all, more than 95% OF API docking code is here, this part of the code occupies a large part of the code, can be interchangeable, replace, test becomes the key choice.

Vue recommended only convert Vuex (Redux migrated to Vue, etc.) React surrounding solutions include Redux, Mobx, etc. These libraries do not have a strong replacement with React (they can stand alone). The idea of state management in both frameworks is similar, both are one-way data flow, singleton pattern (Vue &Redux).

wicks

! [](https://picb.zhimg.com/80/v2-921a1cf07d7872e1191dae588b12119b_720w.jpg)

Vuex source code is not much, you can see here. You can see that there are a lot of things in the code that are strongly bound to Vue, and without Vue, it’s not going to work. You might say, I’ll just use Vue. Why don’t I use React? Consider the following scenario:

  • The project manager wants to migrate Vue’s code to support applets, and suddenly! Some frameworks do not support Vuex, and the head is buzzing
  • The project manager says we need an APP, and suddenly! What a bunch of bugs! Head buzzing
  • The project manager is out of his mind to move the React project to Vue, and suddenly! Redux! Saga! Head buzzing
  • Static problem with state management! It’s gonna take a lot of crap. The new man watched and his head buzzed

This part of the code is more than Vuex source code? These problems are caused by the strong binding between the state management library and the framework, and problems with the framework can also affect the surrounding libraries.

if (version >= 2) {
    Vue.mixin({ beforeCreate: vuexInit })
  } else {
    // override init and inject vuex init procedure
    // for 1.x backwards compatibility.
    const _init = Vue.prototype._init
    Vue.prototype._init = function (options = {}) {
      options.init = options.init
        ? [vuexInit].concat(options.init)
        : vuexInit
      _init.call(this, options)
    }
  }
Copy the code

As you can see, the Vue core upgrade, these accompanying libraries also have to be upgraded and tested. When running in a non-browser environment, due to the volume required by mechanisms such as Vue (or class Vue framework) initialization, relevant libraries such as Vuex are not available, there is an extra code branch, relevant code cannot be replaced, and the burden of testing and refactoring is heavy.

Redux

! [](https://pic2.zhimg.com/80/v2-0e4e89523ffc700c76949158779a65af_720w.jpg)

Redux is one of the most popular state management solutions on React. It is designed to be very simple (see above) and can be used independently, with the associated code easily migrated to different platforms. There are plenty of peripheral alternatives:

  • Blow type
  • redux-promise
  • Redux-Saga
  • Observable

The selection can be referenced here and here. We use saga a lot, and it is relatively easy to deal with static problems, etc. It is not difficult to start by reading more documents. The following graph can help you understand the relationship between the options, the pros and cons.

! [](https://pic2.zhimg.com/80/v2-7748f19a3e30301e4abe52d38ff69b3c_720w.jpg)

Plugins are also available: Redux Middleware. You will find that many of the things you want Vuex does not have!

“In that case, I’ll just use Redux on Vue.”

B: Ok, it will make it easier to move to React later.

The Root of all Evil this pointer

Those of you who have written React functions know that reference class components, function components do not have this pointer, code simplification, clear redundant. The problem is even worse at Vue.

Some people think this is an advantage, easy to use. Wait till you get your code load up.

When you’re working on a project with multiple people working together, or you’re working on someone’s ancestral code, you don’t know if it’s a goat’s head or a dog’s head.

  • The ajax.
  • This HTTP.
  • This message
  • This. WTF…

As one netizen commented:

That thing is the population scope. What’s the difference between “it’s convenient to put anything on the scope” and “it’s convenient to defecate in public”?

Any novice C language writer knows that class variables should not be used at will. Also, this is the official recommended writing method.

Remember I used to write Vue UI library, called Sue-UI, SUE ~ quick look. To avoid conflicts with other plug-ins in the future, use the following:

  • This. $ su_message
  • This. $ su_modal
  • This one. $ su_toast

What a terrible memory!

The last

In terms of framework functions, there is nothing Vue can do that can’t be done by React, and vice versa. Both frameworks can meet functional requirements. In engineering practice, we finally abandoned Vue due to the transformation, code organization, rough upgrade, testing, and exploitation.

In Vue you operate on a defined object, in React you operate on a function. The essence of front-end development is to write the following functions.

S = async(A1)
S = sync(A2)
UI = f(S)
Copy the code

Obviously, the camp abstracts this more thoroughly.

From: zhuanlan.zhihu.com/p/187377658