ref

Ref is a new API for VUe3, which defines a single variable that can be “traced”. In VUe2, all variables need to be defined in data. In Vue3, a setup field is added, which allows us to define variables more flexibly.

vue3

export default defineComponent({
    setup() {
        const countA = ref(1);
        return{ count }; }});Copy the code

vue2

export default {
    data() {
        return { countA: 1}; }};Copy the code

What are the benefits of vuE3’s new API?

The advantage is that THE JS business code can be broken down into more detail. In the example above, countA is the data returned by the interface. Normally, the interface will display a “loading animation” before the request is successful. The display and hiding of this “loading animation” requires a variable control, which is usually called isLoading:

vue2

export default {
    data() {
        return { countA: 1, isLoading };
    },

    async mounted() {
        this.isLoading = true;
        const { data } = await axios.get('/api');
        this.countA = data;
        this.isLoading = false; }};Copy the code

That’s how vue2 is written, and I’m sure that’s how everyone writes it, so it looks like there’s nothing left to wrap, right? Next, try encapsulation with Vue3’s RefAPI:

vue3

export default defineComponent({
    setup() {
        const [isLoading, countA] = useGet('/api');
        return{ isLoading, countA }; }});export function useGet(url) {
    const isLoading = ref(true);
    const dataSource = ref();
    axios
        .get(url)
        .then(({ data }) = > {
            dataSource.value = data;
        })
        .finally(() = > {
            isLoading.value = false;
        });
    return [isLoading, dataSource];
}
Copy the code

Value =false is used to assign a value to isLoading. For more information, see the vUE official documentation

At this point, we found that the scene could not be abstracted, now we can also abstract a useGet, uncle number code just 12 lines.

v-use-axios

Along the above ideas, I made a more complete package of Axios, V-use-Axios, with less code and less logic, about 100 lines. I hope that interested partners can work with me to improve it.

WeChat group

Thank you for your reading. If you have any questions, you can add me to the wechat group, and I will pull you into the wechat group (Because Tencent limits the number of wechat groups to 200, when the number exceeds 200, you must be pulled into the group by group members).