Several ways for vue3 to request data and use it in setup

Because Composition’s combined API setup is a little different, here are some examples of feasible request data and usage methods. The
first kind of Promise
reference code is as follows

<template>
  <div>{
   
   { min }}</div>
</template>

<script>
import {
      
       ref } from 'vue';
import {
      
       getUser } from '@/api/user'
export default {
      
      
  setup(){
      
      
    let min = ref("");
    getUser(30).then(res=>{
      
      
        min.value = res;
    }).catch(err=>{
      
      
      console.log(err);
    })
    return {
      
      
      min
    }
  }
}
</script>

<style>

</style>

The result of the operation is as follows,
insert image description here
which should be the one with the least impact. Basically, it is no different from the previous writing method.

The second is to use async await in other statement cycles. Take onMounted as an example.
The reference code is as follows

<template>
  <div>{
   
   { min }}</div>
</template>

<script>
import {
      
       ref,onMounted } from 'vue';
import {
      
       getUser } from '@/api/user'
export default {
      
      
  setup(){
      
      
    let min = ref("");
    onMounted(async () => {
      
      
      min.value = await getUser(30);
    });
    return {
      
      
      min
    }
  }
}
</script>

<style>

</style>

Here we set async on the lifecycle function of onMounted
and request it through await.
The running results are as follows,
insert image description here
without any side effects, and it looks very standardized and tidy.

The last one is not recommended to use async await directly on the setup.
The reference code is as follows

<template>
  <div>{
   
   { min }}</div>
</template>

<script>
import {
      
       ref } from 'vue';
import {
      
       getUser } from '@/api/user'
export default {
      
      
  async setup(){
      
      
    let min = ref("");
    min.value = await getUser(30);
    return {
      
      
      min
    }
  }
}
</script>

<style>

</style>

But if you use it directly like this, the component will not be loaded. You need to put a pair of suspense outside the place where the component is called.
insert image description here
If the component loaded by the route is directly added to the router-view, it will be fine.

<suspense>
   <router-view />
</suspense>

The running results are as follows
insert image description here
Although the data can be loaded normally, you will find that other asynchronous statement cycles such as onMounted written in the setup will not be executed if you use async directly on the setup. The
third method has many problems, so it is not recommended to use

Personally, I suggest that you can use the second type as much as possible to write the second type, which will be more maintainable.

Guess you like

Origin blog.csdn.net/weixin_45966674/article/details/130841926