Vue3 must learn skills - custom Hooks

1 Introduction:

The official does not clearly specify what is a custom hooks, which is essentially a function, usually used in conjunction with the Composition API,

Extract the reusable logic in the setup function, and introduce and call it on demand to reduce code coupling. Specifically:

  • Extract reusable code logic into external ts files;

  • The function name/file name starts with use, such as useDialog;

  • Responsive variables and methods are deconstructed in the setup function, such as const { visible } = useDialog(false);

2. Specific examples

Implement the hooks function that can control the opening and closing of pop-up windows. First, create a new hooks folder in the project, create a new ts file under the folder, and encapsulate a custom hooks in each file, as shown in the useDialog.ts file in the figure below.

Then define the useDialog function in the file and expose it to external calls. The function internally encapsulates reusable methods such as controlling the display/closing of pop-up windows.

import { ref } from 'vue';

export function useDialog(initValue: boolean) {
    const dialogVisible = ref(initValue);
    function openDialog() {
        dialogVisible.value = true;
    }
    function closeDialog() {
        dialogVisible.value = false;
    }
    function toggleDialog() {
        dialogVisible.value = !dialogVisible.value;
    }
    return {
        dialogVisible,
        openDialog,
        closeDialog,
        toggleDialog,
    };
}

As above, the custom hooks package that can control the closing of the pop-up window is completed. Relevant pages can introduce and call hooks functions as needed. For example, the page shown in the figure below introduces the useDialog function, and deconstructs the required responsive variables and methods in the setup function.

import { useDialog } from '@/hooks/use-dialog';
setup(){
    const { dialogVisible, openDialog } = useDialog(false);
    return {};
}

Guess you like

Origin blog.csdn.net/lfq1996/article/details/129539135