Vue3 setup() advanced usage examples detailed explanation

Vue3 setup() advanced usage examples detailed explanation

This article contains a lot of useful information, so it is recommended that you save it!

Upgrading from vue2 to vue3, vue3 is compatible with vue2, so vue3 can adopt vue2's optional API. Since a variable in the optional API exists in multiple places, if a problem occurs, it is necessary to check in multiple functions. When the project is large, encountering problems increases the difficulty of troubleshooting. Therefore, a new setup configuration item was added in vue3, which is used to write combined APIs.

1. Differences between option API and combination API

Some students have been using Vue for a year without knowing it, but they don’t even know the optional API! Are you that classmate? If yes, collect it quickly.

The Options API in vue2 is an optional API, one in Chinese and one in English, you can call it whatever you want.

In a vue file, there will be data, methods, mounted, computed, watch, etc. used to define properties and methods to handle page logic together. We call this method Options API.

Example 1: Counter

<template>
 <div>
  <button @click="add">+</button>
   {{num}}
  <button @click="reduce">-</button>
 </div>
</template>
<script>
export default {
 data(){
  return {
   num:0
  }
 },
 methods:{
  add(){
   this.num++
  },
  reduce(){
   this.num--
  }
 }
}
</script>

Observing the above example, we find that the processing of num value involves two options: data and methods. The business processing is relatively scattered. When the project is small, it looks clear. However, when the project becomes larger, data and methods will contain many attributes and methods. At this time, it is difficult to distinguish which attribute corresponds to which method. Therefore, vue3 adds a new setup to write a combined API.

Vue3's Composition API is a combination API.

A combined API means that all APIs defined by a function are put together. In this way, even if the project becomes larger and the functions increase, we can quickly find all APIs related to the function. Unlike the Options API, the functions are scattered and when changes are needed, the search process in multiple places is difficult.

Example 2: Counter

<template>
 <div>
  <button @click="add">+</button>
   {{num}}
  <button @click="reduce">-</button>
 </div>
</template>
<script>
 import { ref } from 'vue'
 export default{
  setup(){
   const num = ref(1)
   return {
    num,
    add(){
     num.value++
    },
    reduce(){
     num.value--
   }
  }
 }
}
</script>

Ref makes basic data types responsive. The next article will introduce its usage in detail. If you need it, you can follow it and don’t get lost!

Here is a picture to tell you the difference between them:

2. How to use setup?

2.1. When is setup executed?

setup is used to write combined APIs. From the perspective of lifecycle hook functions, it is equivalent to replacing beforeCreate. Will be executed before creted.

<script>
 export default{
  created(){
   console.log('created');
  },
  setup(){
   console.log('setup');
  }
 }
</script>

After execution, the setup print result is always at the front.

2.2. How to use setup data and methods?

Example 3: Directly define and use variables

<template>
 {{a}}
</template>
<script>
 export default{
  setup(){
   const a = 0
  }
 }
</script>

After running, the results are abnormal:

runtime-core.esm-bundler.js?5c40:6584 [Vue warn]: Property "a" was accessed during render but is not defined on instance.

It prompts us that the attribute a we accessed is not mounted on the instance.

The properties and methods inside setup must be exposed by return, so that the properties can be mounted on the instance, otherwise they cannot be used. The above code adds return:

<script>
 export default{
  setup(){
   const a = 0
   return {
    a
   }
  }
 }
</script>

2.3. Is there this inside setup?

Print this in setup and the result is undefined. This means that this does not exist inside setup, and things related to this cannot be mounted.

2.4. How to use the hook function in setup?

Vue3 is compatible with the option-based writing style of Vue2, so the hook function can exist in parallel with the setup, which is equivalent to the Options API.

Example 4:

export default{
 setup(){
  console.log('setup');
 },
 mounted(){
  console.log('mounted');
 }
}

The setup() function added by vue3 is used to write combined APIs, so it is not recommended to write code in this way. Therefore, you need to use the onXXX family of functions to register the hook function. After successful registration, a callback function is passed when it is called.

Example 5:

import { onMounted } from "vue";
export default{
 setup(){
  const a = 0
  return {
   a
  },
  onMounted(()=>{
   console.log("execution");
 })
 }
}

These registered lifecycle hook functions can only be used synchronously during setup, because they rely on global internal state to locate the current component instance, and an error will be thrown if the function is not called under the current component.

The other hook functions are the same, just introduce them as needed.

2.5. Relationship between setup and hook functions

When setup is listed in parallel with the hook function, setup cannot call lifecycle related functions, but the lifecycle can call setup related properties and methods.

Example 6:

<template>
 <button @click="log">Click me</button>
</template>
<script>
export default{
 setup(){
  const a = 0
  return {
   a
  }
 },
 methods:{
  log(){
   console.log( this.$options.setup() ); // returns an object }
 }
}
</script>

this.$options.setup() returns a large object that contains all the properties and methods in setup.

3. setup parameters

When using setup, it will receive two parameters: props and context.

3.1. props

The first parameter is props, which means that the parent component passes values ​​to the child component. Props are responsive and automatically updated when new props are passed in.

Example 7:

export default{
 props: {
  msg: String,
  ans: String,
 },
 setup(props,context){
  console.log(props); //Proxy {msg: "Looking for a partner urgently", ans: "Do you have a partner?"}
 },
}

Because props is responsive, ES6 destructuring cannot be used, which will eliminate the responsiveness of props. In this case, toRefs destructuring is needed. Example 8:

import { toRefs } from "vue";
 export default{
  props: {
   msg: String,
   ans: String,
  },
  setup(props,context){
   console.log(props);
   const { msg, ans } = toRefs(props)
   console.log(msg.value); //Anxiously looking for a partner console.log(ans.value); //Do you have a partner?
  },
 }

When using components, you often encounter optional parameters. Sometimes you need to pass a value, but sometimes you don't. How do you deal with it?

If ans is an optional parameter, then ans may not be present in the passed props. In this case toRefs will not create a ref for ans and you need to use toRef instead.

import { toRef } from "vue";
setup(props,context){
 let ans = toRef(props ,'ans') // If it does not exist, create an ans
 console.log(ans.value);
}

3.2, context

context context environment, which includes three parts: attributes, slots, and custom events.

setup(props,context){
 const { attrs, slots, emit } = context
 // attrs gets the attribute value passed by the component,
 // slots in the slots component // emit custom event subcomponent}

attrs is a non-responsive object that mainly receives no-props attributes and is often used to pass some style attributes.

slots is a proxy object, where slots.default() gets an array whose length is determined by the component's slots and contains the slot contents.

This does not exist in setup, so emit is used to replace the previous this.$emit, and is used to trigger custom events when passing from child to parent.

Example 9:

<template>
 <div :style="attrs.style">
  <slot></slot>  
  <slot name="hh"></slot>
  <button @click="emit('getVal','Pass value')">Child passes value to parent</button> 
 </div> 
</template>
<script>
import { toRefs,toRef } from "vue";
export default{
 setup(props,context){
  const { attrs, slots, emit } = context
  // attrs gets the style attribute passed by the component console.log('slots', slots.default()); // slot array console.log('slot attributes', slots.default()[1].props); // Get the attributes of the slot return {
  attrs,
  emit
   }
  },
 }
</script>

4. Summary of setup features

1. This function will be executed before created, as explained above.

2. There is no this inside setup, so things related to this cannot be mounted.

3. The properties and methods inside setup must be returned and exposed, otherwise they cannot be used.

4. The data inside setup is not responsive.

5. Setup cannot call lifecycle related functions, but lifecycle functions can call functions in setup.

This is the end of this article about the advanced usage of vue3 setup(). For more relevant vue3 setup() usage content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of the setup syntax sugar example for Vue3 update
  • Vue3 - setup script usage experience sharing
  • Front-end vue3 setup tutorial
  • Application example of setup-script in vue3
  • Vue3 based on script setup syntax $refs usage
  • Highly recommended! Setup syntax sugar in Vue 3.2
  • setup+ref+reactive implements vue3 responsiveness
  • About the use of setup function in vue3

<<:  The process of setting up an environment for integration testing using remote Docker

>>:  Sending emails in html is easy with Mailto

Recommend

In-depth understanding of the life cycle comparison between Vue2 and Vue3

Table of contents Cycle comparison usage Summariz...

Detailed explanation of the this pointing problem in JavaScript

Summarize Global environment ➡️ window Normal fun...

Using zabbix to monitor the ogg process (Windows platform)

This article introduces how to monitor the ogg pr...

Detailed explanation of Linux text processing tools

1. Count the number of users whose default shell ...

How to implement responsive layout in vue-cli

When we are doing front-end development, we will ...

Configure nginx to redirect to the system maintenance page

Last weekend, a brother project was preparing to ...

Tutorial on building a zookeeper server on Windows

Installation & Configuration The official web...

Implementation of breakpoint resume in vue-video-player

In a recent project, I needed to implement the fu...

Forever+nginx deployment method example of Node site

I recently bought the cheapest Tencent cloud serv...

Vue example code using transition component animation effect

Transition document address defines a background ...

The whole process of configuring hive metadata to MySQL

In the hive installation directory, enter the con...

Solution to the data asymmetry problem between MySQL and Elasticsearch

Solution to the data asymmetry problem between My...

Complete steps to install FFmpeg in CentOS server

Preface The server system environment is: CentOS ...

What does the legendary VUE syntax sugar do?

Table of contents 1. What is syntactic sugar? 2. ...

Advertising skills in the Baidu Union environment (graphic tutorial)

Recently, students from the User Experience Team o...