Those things about setup syntax sugar in vue3

What is syntactic sugar?

⭐Syntactic sugar refers to a special grammatical form in a programming language. It does not affect the functions and capabilities of the language, but only provides a more elegant, concise, and easy-to-read grammatical form, making the code easier to understand and write. Usually, syntactic sugar is the process by which the compiler or interpreter converts the code into standard syntax when compiling or interpreting it. Therefore, syntactic sugar does not increase the operating efficiency of the code, but only improves the readability and maintainability of the code.

In front-end development, there are many common syntactic sugars, such as:

  • The arrow function in ES6 can simplify the writing of function definition;
  • V-bind in Vue can be written as a colon, and v-on can be written as an @ symbol, which can simplify the writing of binding events and attributes in templates;
  • The JSX syntax in React can combine HTML and JavaScript to make the code more readable.

In general, syntactic sugar can improve the readability and maintainability of your code, but you also need to be careful not to overuse it so as not to affect the performance and understandability of your code.


What new syntactic sugar does vue3 have compared to vue2?

⭐First of all, it needs to be clear that compared with vue2, vue3 has many new writing methods and syntactic sugar, mainly based on the implementation of Composition API.

ref

Used in Vue3 refto define responsive data, its usage is similar to data in Vue2.

import {
    
     ref } from 'vue'

export default {
    
    
  setup() {
    
    
    const count = ref(0)

    return {
    
    
      count
    }
  }
}

reactive

reactiveFunctions are used to create reactive objects, which can convert an ordinary object into a reactive object. Similar to the one in Vue2 computed, the one in Vue3 computedis also reactiveimplementation-based.

import {
    
     reactive, computed } from 'vue'

export default {
    
    
  setup() {
    
    
    const state = reactive({
    
    
      count: 0,
      doubleCount: computed(() => state.count * 2)
    })

    return {
    
    
      state
    }
  }
}

watch

Functions in Vue3 watchcan monitor changes in responsive data, and their usage is watchsimilar to that in Vue2.

import {
    
     watch } from 'vue'

export default {
    
    
  setup() {
    
    
    const count = ref(0)

    watch(count, (newValue, oldValue) => {
    
    
      console.log(`count的值从${
      
      oldValue}变为${
      
      newValue}`)
    })

    return {
    
    
      count
    }
  }
}

life cycle

In Vue3, the lifecycle hook function is refactored into setupa normal function in the function, for example, createdthe hook function can be split into beforeCreatetwo createdfunctions

import {
    
     onBeforeCreate, onCreated } from 'vue'

export default {
    
    
  setup() {
    
    
    onBeforeCreate(() => {
    
    
      console.log('组件实例创建之前')
    })

    onCreated(() => {
    
    
      console.log('组件实例创建之后')
    })

    return {
    
    }
  }
}

Teleport

A new component is added in Vue3 Teleport, which is used to insert the content of the component into the specified DOM node, and its usage is slotsimilar to that in Vue2

<template>
  <teleport to="body">
    <div>Teleport到body中了</div>
  </teleport>
</template>


setup syntactic sugar

⭐⭐The setup function is a new feature in Vue3. It is used to replace the data, computed, watch and other options in Vue2. It is a new component option. It can be said that the setup function is one of the most important syntactic sugar in Vue3.

The setup function is an ordinary function that receives two parameters: props and context. Among them, props is the attribute object of the component, and context is the context object of the component, including some Vue3 APIs.

In the setup function, we can use the Composition API provided by Vue3 to define the component's responsive data, computed properties, methods, life cycle hooks, etc. Unlike the options in Vue2, the code in the setup function is pure JavaScript code, which is easy to understand and maintain.

In addition, the setup function has the following features:

  • The return value of the setup function is an object, and the properties and methods in the object can be used directly in the template.
  • The reactive data in the setup function must be created using APIs such as ref and reactive, and cannot be directly defined in the setup function.
  • Computed properties and methods in the setup function can be directly defined as ordinary functions without using the computed and methods options.
  • The lifecycle hook function in the setup function has also been refactored, and can be defined using onBeforeMount, onMounted and other APIs.

<script setup>How is it different from traditional vue3

<script setup>is a new feature in Vue 3 that aims to simplify writing single-file components. Compared with the tags in traditional Vue 3 <script>, <script setup>it has the following differences:

  • No need to import the vue module: <script>you need to import the vue module when using Vue in tags, but <script setup>not in .
  • There is no need to define data、computed、methodsoptions such as: In <script>the tag, you need to define the responsive data through the data function, and define the calculation properties and methods under the computedand methodsoptions. But <script setup>you can use responsive variables and computed properties directly in , and these variables and properties will be automatically processed as responsive.
  • propsAnd contextobject automatic injection: <script setup>You can use propsand contextobject directly in , without getting it through parameters or import.
  • Single-file components support more types: In addition to .vue files, use .tsxand .jsxfiles are also supported as single-file components and can be <script setup>used with .

⭐⭐⭐When converting traditional Vue 3 code to <script setup>code, the main methods are summarized, there are about 4 kinds:

⭐The first method: Just declare the responsive variable that was originally placed under the data option directly, for example, the

 data: () => ({
    
     
   num: 10
  })

replace with

const num = ref(10)

⭐Second method: Computed properties can be directly declared as functions and return values; methods can also be directly declared as functions


⭐The third type: <template>Responsive variables and computed properties used in tags need to be defineExposeexposed before they can be used in parent components. For example:

const state = reactive({
    
     
	count: 0 
}); 

defineExpose({
    
     state });

⭐Fourth: propsand contextthe object can be declared directly in the function parameter

The life cycle function is written in the same way as the traditional Vue 3, and can continue to be used


Traditional vue3 and setup syntax sugar, how to convert between the two?

Here, I will directly explain a piece of code.

⭐Traditional vue3 writing method:

<template>
  <div>{
    
    {
    
     count }}</div>
</template>

<script>
import {
    
     reactive } from "vue";

export default {
    
    
  data: () => ({
    
    
    count: 0
  }),
  
  methods: {
    
    
    increment() {
    
    
      this.count++;
    }
  },
  
  created() {
    
    
    console.log('语法糖你好');
  }
};
</script>

⭐Writing with setupsyntactic sugar

<template>
  <div>{
    
    {
    
     count }}</div>
</template>

<script setup>
import {
    
     ref, onMounted } from 'vue'

let count = ref(0)

function increment() {
    
    
   count.value++
}

onMounted(() => {
    
    
   console.log('语法糖你好')
})
</script setup>

This kind of technology, writing, and concept renewal is actually very good, and it is normal that it will be difficult to accept for a while. But the new way of writing will make our code more concise, flexible, and easy to maintain. It also enables us to better organize the code and improve development efficiency.

Cheers to syntactic sugar!

insert image description here

Guess you like

Origin blog.csdn.net/dyk11111/article/details/131052755