Vue source code analysis and practice

This article: I am 970 original link: juejin.cn/post/704076…

✨ opening

RT, why are we on Vue3? Does using Vue3 affect me driving a ferrari?

After the recent release of Vue3 version 3.2, there are more and more articles on The Nuggets about Vue3. I wanted to keep the bullet flying for a while, but the company recently joined the Vue3 project and started to learn it myself.

Yesterday, I was a big believer in Vue2’s Options API, but today, after doing Vue3’s Composition API, I’m calling Vue3 really cool!

Next, we’ll start with an analysis of Vue2’s strengths and weaknesses, as well as a combination of images and use cases to understand Vue3’s strengths.

Vue2 ⚔ Vue3

Vue2

advantages

There is no denying the success of Vue2. In Github’s front-end classification, we can also see that Vue warehouse ranks first, with enough fans and active users

That’s 12K + star more than React

From my point of view, the biggest contributors are these three:

  • Responsive data
  • Options API
  • SFC

In addition to these three masters, Vuex/ VuE-Router, as well as rich peripheral plug-ins and an active community, are indispensable.

disadvantages

It is clear to use the Options API to write a component when it is performing a single piece of logic.

However, in our actual business scenario, a parent component always contains multiple child components, and the parent component needs to pass values to the child component, handle the child component events, operate the child component directly, and deal with various logic of the call interface, when the logic of our parent component will become complicated.

From the point of view of code maintainer, suppose there are 10 function methods at this time, naturally we need to add them into methods, and these 10 function methods operate 10 data respectively, and these 10 data need Watch operation respectively.

At this time, according to the writing method of Options API of Vue2, we finished writing 10 methods, 10 data and 10 watch. We divided the original 10 function methods into 30 different places.

The parent component’s code is unfriendly to the code maintainer.

Some people may say, so write can increase the amount of code, the boss kua I cow force! Hahaha 😂

Vue3

advantages

Freedom, freedom, fucking freedom!

  • Better performance, better tree shaking
  • Composition API + setup
  • Better support for TypeScript

Possible disadvantages

Vue3: Let your freedom go too far

After a spirited performance on the setup stage using the Composition API, one question may arise: How do you elegantly organize your code?

Code is not elegantly organized, and it is also difficult to maintain after the code volume has increased.

SFC writing changes

Vue2 is a normal Vue file

<template>
  <div>
    <p>{{ person.name }}</p>
    <p>{{ car.name }}</p>
  </div>
</template>

<script>
export default {
  name: "Person".data() {
    return {
      person: {
        name: "Xiao Ming".sex: "male",},car: {
        name: "BMW".price: "40w",}}; },watch: {'person.name': (value) = > {
          console.log('the name has been changed to${value}`)},'person.sex': (value) = > {
          console.log('Gender has been changed, changed to${value}`)}},methods: {
    changePersonName() {
      this.person.name = "Little sea";
    },

    changeCarPrice() {
      this.car.price = "80w"; }}};</script>
Copy the code

Rewrite using Vue3 Composition API

<template>
  <p>{{ person.name }}</p>
  <p>{{ car.name }}</p>
</template>

<script lang="ts" setup>
import { reactive, watch } from "vue";

// The logic of person
const person = reactive<{ name: string; sex: string }>({
  name: "Xiao Ming".sex: "male"}); watch(() = > [person.name, person.sex],
  ([nameVal, sexVal]) = > {
    console.log('the name has been changed to${nameVal}`);
    console.log('the name has been changed to${sexVal}`); });function changePersonName() {
  person.name = "Little sea";
}

// Car logic
const car = reactive<{ name: string; price: string }>({
  name: "BMW".price: "40w"});function changeCarPrice() {
  car.price = "80w";
}
</script>
Copy the code

Vue3 custom Hook is adopted to further split

<template>
  <p>{{ person.name }}</p>
  <p>{{ car.name }}</p>
  <p>{{ animal.name }}</p>
</template>

<script lang="ts" setup>
import { usePerson, useCar, useAnimal } from "./hooks";

const { person, changePersonName } = usePerson();

const { car } = useCar();
</script>
Copy the code
// usePerson.ts
import { reactive, watch } from "vue";

export default function usePerson() {
  const person = reactive<{ name: string; sex: string({} >name: "Xiao Ming".sex: "male"}); watch(() = > [person.name, person.sex],
    ([nameVal, sexVal]) = > {
      console.log('the name has been changed to${nameVal}`);
      console.log('the name has been changed to${sexVal}`); });function changePersonName() {
    person.name = "Little sea";
  }
  return {
    person,
    changePersonName,
  };
}
Copy the code
// useCar.ts
import { reactive } from "vue";

export default function useCar() {
  const car = reactive<{ name: string; price: string({} >name: "BMW".price: "40w"});function changeCarPrice() {
    car.price = "80w";
  }
  return {
    car,
    changeCarPrice,
  };
}
Copy the code

After the comparison, Vue3 allows us to better organize our code. The logic for person and car is placed separately

Is it just the advantage of code organization? No, no, no, let’s look at some changes in the template

  • <template>The start note in the label can not be used<div>Tag, becauseVue3providesfragmentThe ability to useVue-detoolsYou can see that there arefragmentThe tag

  • WatchI don’t need to list more than one,Vue3Supports listening on multiple sources in
  • Very natural to useTypeScriptThe type constraint is simpler

performance

Vue3 mainly improves in these aspects

  1. Compilation phase. Diff algorithm optimization, static lifting and so on
  2. Responsive systems.Proxy()alternativeObject.defineProperty()Listening object. Listen to an object, no more deep traversal,Proxy()You can hijack the whole thing
  3. Volume package reduced. The Compostion API is written in a way that makes tree shaking better, reduces context-free code and reduces the size of packaged files
  4. newfragmentFeatures. Vue file<template>Tag inside, no longer need to enforce a declaration of<div>Tag to save extra node overhead

🎤 summary

There are many more advantages and new features of Vue3. This article mainly introduces why we want to use Vue3 from the advantages and disadvantages of VUe2/3 version and the changes of SFC writing method.

Vue3 smells good and supports TypeScript better, making Vue3 the first choice for enterprise-level Vue projects, and new features cater to trends in front-end technology.

Ie browser: Then I go?

👓 finally

What is Vue3?

If this article is helpful to you, then bother you to move your little hands and point a thumbs-up 👍, each of your thumbs-up points is a great encouragement for me to continue to create!

The resources

Interviewer: What are the main aspects of Vue3.0 performance improvement?

Vue3 Tutorial: Where is Vue 3.x Fast?

other

It’s the last day of the Nuggets creator of the Year list, so please vote for our team. The front-end development team is grateful for your support