ホームページ  >  記事  >  ウェブフロントエンド  >  async/await を使用して Vue で非同期操作を処理する方法

async/await を使用して Vue で非同期操作を処理する方法

WBOY
WBOYオリジナル
2023-06-11 09:18:115052ブラウズ

async/await を使用して Vue で非同期操作を処理する方法

フロントエンド開発の継続的な開発に伴い、Vue でより複雑な非同期操作を処理する必要があります。 Vue は非同期操作を処理するための便利な方法をすでに多数提供していますが、場合によっては、これらの非同期操作を処理するために、よりシンプルで直感的な方法を使用する必要がある場合があります。現時点では、async/await は非常に良い選択になります。

非同期/待機とは何ですか?

ES2017 では、async と await が 2 つの新しいキーワードになります。 async は、関数が非同期関数であることを示すように関数を変更するために使用されます。非同期関数では、 await を使用して Promise オブジェクトを待機し、オブジェクトの値を取得できます。

Vue では、通常、インターフェースを呼び出してデータを取得したり、画像を非同期でロードしたりするなど、Promise ベースの非同期操作を使用します。 async/await を使用すると、これらの非同期操作をより明確に処理できるようになります。

async/await を使用するにはどうすればよいですか?

async/await を使用するための基本的な構文は非常に簡単です。関数を非同期関数として宣言し、非同期操作を待機する必要がある Promise オブジェクトの戻り値を待機するために await を使用するだけです。

データ取得を例に挙げると、非同期関数 getArticleById を定義し、関数本体で http リクエストの戻り値を待つことができます。

async function getArticleById(id) {
    const response = await fetch(`/api/articles/${id}`);
    return response.json();
}

Vue では通常、次のように使用します。 axios はデータを取得するインターフェイスを呼び出します。 axios を非同期関数にカプセル化し、Vue コンポーネントで async/await を使用してデータを取得できます。

ブログ リストの取得を例として、非同期関数 getBlogList:

async function getBlogList() {
    const response = await axios.get('/api/blogs');
    return response.data;
}

を定義できます。次に、Vue コンポーネントで async/await を使用してデータを取得し、データをテンプレートに入力します:

<template>
    <div>
        <div v-for="blog in blogs" :key="blog.id">{{blog.title}}</div>
    </div>
</template>

<script>
    async function getBlogList() {
        const response = await axios.get('/api/blogs');
        return response.data;
    }

    export default {
        data() {
            return {
                blogs: []
            }
        },
        async mounted() {
            this.blogs = await getBlogList();
        }
    }
</script>

async/await を使用して複数の非同期操作を処理する

実際の開発では、通常、複数の非同期操作を同時に処理する必要がある状況に遭遇します。たとえば、Vue コンポーネントでは、さまざまなインターフェイスからデータを取得し、それを処理またはレンダリングする必要があります。現時点では、Promise.all() メソッドを使用して、すべての非同期操作が一度に完了するのを待つことができます。

記事とコメントの取得を例として、2 つの非同期関数 getArticle と getComments を定義できます。

async function getArticle(id) {
    const response = await axios.get(`/api/articles/${id}`);
    return response.data;
}

async function getComments(articleId) {
    const response = await axios.get(`/api/articles/${articleId}/comments`);
    return response.data;
}

次に、Promise.all を使用して、これら 2 つの非同期操作を 1 つの非同期関数にカプセル化できます。 () は両方の操作が同時に完了するのを待ちます:

async function getArticleWithComments(articleId) {
    const [ article, comments ] = await Promise.all([
        getArticle(articleId),
        getComments(articleId)
    ]);
    return {
        article,
        comments
    };
}

Vue コンポーネントでは、async/await を使用してすべてのデータを取得し、データをテンプレートにバインドできます:

<template>
    <div>
        <h1>{{article.title}}</h1>
        <p>{{article.content}}</p>
        <ul>
            <li v-for="comment in comments" :key="comment.id">{{comment.content}}</li>
        </ul>
    </div>
</template>

<script>
    async function getArticle(id) {
        const response = await axios.get(`/api/articles/${id}`);
        return response.data;
    }

    async function getComments(articleId) {
        const response = await axios.get(`/api/articles/${articleId}/comments`);
        return response.data;
    }

    async function getArticleWithComments(articleId) {
        const [ article, comments ] = await Promise.all([
            getArticle(articleId),
            getComments(articleId)
        ]);
        return {
            article,
            comments
        };
    }

    export default {
        data() {
            return {
                article: {},
                comments: []
            }
        },
        async mounted() {
            const data = await getArticleWithComments(this.$route.params.articleId);
            this.article = data.article;
            this.comments = data.comments;
        }
    }
</script>

try/catch を使用して例外を処理する

非同期関数を使用する場合は、例外処理にも注意する必要があります。非同期関数でエラーが発生した場合、try/catch ステートメントを使用して例外をキャッチし、それに応じて処理できます。

ユーザー情報の取得を例として、非同期関数 getUserInfo を定義できます。ユーザーがログインしていない場合、サーバーからユーザー情報を取得する際に不正なエラーが返されます。 try/catch ステートメントを使用してエラーをキャプチャし、それに応じて処理できます:

async function getUserInfo() {
    try {
        const response = await axios.get('/api/user');
        return response.data;
    } catch (error) {
        if (error.response && error.response.status === 401) {
            // 用户未登录
            return null;
        } else {
            // 其它异常
            throw error;
        }
    }
}

Vue コンポーネントでは、async/await を使用してユーザー情報を取得し、戻り値に基づいて適切に処理できます:

<template>
    <div>
        <div v-if="user">{{user.name}},欢迎回来!</div>
        <div v-else>请先登录</div>
    </div>
</template>

<script>
    async function getUserInfo() {
        try {
            const response = await axios.get('/api/user');
            return response.data;
        } catch (error) {
            if (error.response && error.response.status === 401) {
                // 用户未登录
                return null;
            } else {
                // 其它异常
                throw error;
            }
        }
    }

    export default {
        data() {
            return {
                user: null
            }
        },
        async mounted() {
            this.user = await getUserInfo();
        }
    }
</script>

概要

async/await を使用すると、Vue での非同期操作をより明確に処理できるようになります。 async/await を使用して Promise オブジェクトの戻り値を待機し、Promise.all() を使用して複数の非同期操作が一度に完了するのを待機できます。同時に、非同期関数を使用する場合は、try/catch ステートメントを使用して非同期操作の例外をキャッチする例外処理にも注意する必要があります。

以上がasync/await を使用して Vue で非同期操作を処理する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。