preface

Stare, the third digger of Fat Jean is coming! I recently made a vuE3 list in my plan. About vue3, although have long seen it before, but also just know some simple wrote several small demo, and our main technology stack is vue, while the recent study of strength, hurry up to apply for an internal project, with vue3 practice a wave, some hope that this article summarize the junior partner to provide some help.

The following will be summarized from two parts: one part is possible confusion or some common problems, and the other part is pit points/attention points encountered in practice.

Some questions about vue3

1: With Vue3, should I follow the Composition API to write the page?

The answer is no. One thing to note: Vue3 doesn’t scrap the Options API, and even fully supports work that is compatible with Vue2 syntax. The background of the CompositionAPI is mainly to solve the problems of logical abstraction and reuse, but it does not mean that it has become the standard of Vue3. So, how to distinguish scenes using Options API or Composition API mainly depends on complex programs of business logic, such as some simple basic components such as toast/button. Using Options API form will be clearer and concise. For relatively complex business logic, Composition API can be used to extract a single piece of logic into a module and solve the problem through hook functions.

2: Will the use of the Options API and Composition API in Vue3 affect performance?

Don’t. In fact, it is obvious from Question 1 that there is no performance impact. You should not be limited by the Option API and focus more on logical cohesion

3: The problem with not having this in setup

The official VUE documentation explains: Inside setup(), this is not a reference to the active instance, because setup() is called before other component options are parsed, so this inside setup() behaves completely differently than this in other options. This can cause confusion when using setup() with other optional apis. This means that you will not be able to access any properties declared in the component – local state, computed properties/methods – except props.

This function cannot access this because it does not pass the component instance to Setup when it executes the setup function. I don’t refer this to instance. The beforeCreate hook is not mounted, and the beforeCreate hook is not mounted, and the beforeCreate hook is not mounted.

4: reactive VS ref

When you first look at the document, people tend to compare these two and summarize:

Reactive APIS: Make an object data reactive (equivalent to vue.Observable () in 2.x), and Composition APIS recommend active user definition of reactive data rather than internal black box processing

Ref: The value of an array or object is reactive

Another note about toRefs: Using toRefs to return reactive pairs of objects for composite functions essentially does a layer of getter and setter processing for us, so deconstruction can get reactive data, which reduces some of the mental burden associated with refs

5: Is the performance of Vue3 responsiveness better than Vue2?

When VUE3 comes out, some of the answers you often hear are that VUE3 is better than Vue2, but is it true? During the release of Vue3 (I also went to collect the wool to learn about the 1 yuan source code class analysis: Old Huang YYDS), even in the group everyone was discussing this issue.

First of all, in terms of implementation: As we all know, responsivity in VUe2 is mainly attributed to Object.defineProperty, which mainly hijades the attributes of the Object, so it cannot observe the addition and deletion of the attributes of the Object. In Vue, it is implemented by Proxy, which hijades the whole Object and can avoid the problems left by VUe2. But there is also an obvious disadvantage is not strong compatibility. But compared to Vue2, you need to know that the performance advantage of VUE3 is mainly in the initialization phase. Because when Vue2 locates a reactive object, it recursively changes the child object into a reactive object. Vue3, on the other hand, is lazy execution: the child objects are recursively rendered responsive only when the object properties are actually accessed.

6: Vue Composition API VS React Hooks

Vue3’s Composition API is similar to that of React Hooks, so we can’t help but compare them. About the PK of this part, our partner has already summarized it in a comprehensive way, so I won’t go into details about it: portal:

Vue Composition API vs. React Hooks

List of practical issues

In addition to some common problems, what is more important is practice. For new projects, vue3 can be directly used to start, but for more existing projects, when vuE2 is upgraded to vue3 practice, there will certainly be a lot of pits. The following are some points of attention that may be encountered in the process of practice & pits

Script Setup is still an experimental new feature and has not yet been released as an official feature. It is not clear if there will be any changes.

[@vue/compiler-sfc] <script setup> is still an experimental proposal. Follow its status at https://github.com/vuejs/rfcs/pull/227. [@vue/compiler-sfc] When using experimental features, it is recommended to pin your vue dependencies to exact versions to avoid breakage. [@vue/compiler-sfc] `defineProps` is  a compiler macro and no longer needs to be imported.Copy the code

2: When vue3 is migrated, only what is left in Setup is no longer available
o n . on,
Once, $off, etc., only emit, as follows:

setup(props, { emit }) { const rootRef = ref(null) const scroll = useScrolll(rootRef, props, emit) return { rootRef, On ('scroll', pos => {emit('scroll', pos)})Copy the code

3: About computed: 3.X turns computed into a computed attribute API, so you can have multiple computed objects, and you can use the same method as vue.js 2. X

// vue2.x computed: { loading() { return ! this.list.length } }, // vue3.x const loading = computed(() => ! this.list.length) const titleList = computed(() => { return props.data.map((item) => item.title) })Copy the code

4: About watch: If the listener is a delimited string, you need to specify deep: true in the option argument

// vue2.x
watch: {
    'data.distance': function (newVal, oldVal) {
      if (newVal === constants.DISTANCE_ON) {
        ...
      }
    },
},


// vue3.x
watch(
   () => this.data.distance,
   (newVal, oldVal) => {
        if (newVal === constants.DISTANCE_ON) {
            ...
        }
   },
   { deep: true },
 )

Copy the code

5:Vue3The component infiltersOption, available during migrationcomputed/methodsalternative

// vue2.x
filters: {
    // just a method
    dateFormat,
},


// vue3.x
const dateFormat = computed(() => {
    // just a method
    dateFormat,
})
Copy the code

You can use multiple bidirectional bindings on the same component, and you can use custom V-Model modifiers

6: vue3.X was removed.syncwithv-modelInstead of just one componentv-model

// vue2.x
<basic-info-dialog :shown.sync="dialogFormVisible">
<ChildComponent v-bind:name.sync="name" />

// vue3.x
<basic-info-dialog v-model:shown="dialogFormVisible">
Copy the code

conclusion

Step pit still continue, continue to practice continue to step!

The resources

Vue documentation: vue3js.cn/docs/zh/gui…

Vue Composition API 和 React Hooks 对比:juejin.cn/post/