Vue3 makes asynchronously fetched data objects responsive based on a combined API

In Vue 3, you can use refthe and reactiveto make asynchronously fetched data reactive.

1. Useref

First, use refthe function to create a reactive primitive data type, such as a string, number, or boolean. Then, update the value of the refobject . Since refthe object is responsive, the component will automatically re-render when the data changes.

For example, suppose there is a function to get data asynchronously fetchData(), after getting the data, you can save it in an refobject :

import { ref } from "vue";

export default {
  setup() {
    const data = ref(null);

    const fetchData = async () => {
      const response = await fetch("https://example.com/data");
      const result = await response.json();
      data.value = result;
    };

    fetchData();

    return {
      data,
    };
  },
};

 

In the example above ref, a datareactive object named is created using the function and its initial value is set to null. Then, in fetchDatathe function , use fetchthe function to get the data asynchronously and save it in data.valuethe . Since datathe object is responsive, the component will automatically re-render when its value changes.

Two, usereactive

In addition to refthe function , you can also use reactivethe function to create a reactive object. For example, suppose there is a function to get data asynchronously fetchData(), after getting the data, you can save it in an reactiveobject :

import { reactive } from "vue";

export default {
  setup() {
    const data = reactive({
      value: null,
    });

    const fetchData = async () => {
      const response = await fetch("https://example.com/data");
      const result = await response.json();
      data.value = result;
    };

    fetchData();

    return {
      data,
    };
  },
};

 

In the example above reactive, a datareactive object named is created using the function and its initial value is set to { value: null }. Then, in fetchDatathe function , use fetchthe function to get the data asynchronously and save it in data.valuethe . Since datathe object is responsive, the component will automatically re-render when its value changes.

In short, using refthe and reactivecan easily make the data fetched asynchronously responsive, so as to realize the dynamic update and automatic re-rendering of the data.

Guess you like

Origin blog.csdn.net/lwf3115841/article/details/130531435