vue3 encapsulates ajax

Vue 3 is used  Composition API, of which  ref and  reactive are the most commonly used, we can use them to encapsulate Ajax. In the past, we needed to import jQuery or other third-party libraries to make Ajax requests, but now, we can use native  fetch functions or  axios encapsulate them. Here is  fetch an example of using functions for encapsulation:

import { ref } from 'vue';

export function useHttp() {
  const loading = ref(false);
  const data = ref(null);
  const error = ref(null);

  async function get(url) {
    loading.value = true;
    try {
      const response = await fetch(url);
      const responseData = await response.json();
      data.value = responseData;
    } catch (error) {
      error.value = error.message;
    } finally {
      loading.value = false;
    }
  }

  return { loading, data, error, get };
}

In the above code, we used to  ref define three variables  loading, data and  error, and initialized them all to  null or  false. These variables change when an Ajax request is made.

async function get(url) Indicates that we need to pass in a URL to make an Ajax request. Then, we'll  loading set it to  true, indicating that we're making an Ajax request. We use  fetch a function to make an Ajax request and wait for the response, then we assign the response data to  data.

If an error occurs, we assign the error message to  errorand then  loading set to to  falseindicate that the Ajax request has completed.

Finally, we  return loading, data, error and  get as an object to be called in the component.

Here's how to use encapsulated  get methods in components:

import { useHttp } from '../utils/http';

export default {
  setup() {
    const { loading, data, error, get } = useHttp();

    onMounted(() => {
      get('http://localhost:3000/data').then(() => {
        console.log(data.value);
      });
    });

    return { loading, data, error };
  }
};

In the component, we  useHttp obtain  loading, data, error and  through methods get, and then  onMounted call  get the method in the life cycle hook to obtain the data. After  get the method is completed, we can  data access the obtained data. If an error occurs, we can  error access the error message and display it if needed.

Guess you like

Origin blog.csdn.net/weixin_42602736/article/details/130871062