In Vue 3, you can use ref
the and reactive
to make asynchronously fetched data reactive.
1. Useref
First, use ref
the function to create a reactive primitive data type, such as a string, number, or boolean. Then, update the value of the ref
object . Since ref
the 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 ref
object :
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 data
reactive object named is created using the function and its initial value is set to null
. Then, in fetchData
the function , use fetch
the function to get the data asynchronously and save it in data.value
the . Since data
the object is responsive, the component will automatically re-render when its value changes.
Two, usereactive
In addition to ref
the function , you can also use reactive
the 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 reactive
object :
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 data
reactive object named is created using the function and its initial value is set to { value: null }
. Then, in fetchData
the function , use fetch
the function to get the data asynchronously and save it in data.value
the . Since data
the object is responsive, the component will automatically re-render when its value changes.
In short, using ref
the and reactive
can easily make the data fetched asynchronously responsive, so as to realize the dynamic update and automatic re-rendering of the data.