[Vuex] Perform Async Updates using Vuex Actions with TypeScript

Mutations perform synchronous modifications to the state, but when it comes to make an asynchronous operation, they become useless.

Actions are a higher layer on the Vuex pattern, which allow to call mutations asynchronously or even call multiple mutations. This lesson guides you through using Vuex actions and type-safe them with TypeScript.

 

We want to add a todo by calling a API to get a todo from a server, then add into our todo app.

The idea is using 'Actions' to make Async request, then calling 'Mutations' with response data.

复制代码
import {GetterTree, MutationTree} from 'vuex';
import {State} from '../types';
import {Todo} from '../types';

const state: State = {
    todos: [
        {text: 'Buy milk', checked: false},
        {text: 'Learning', checked: true},
        {text: 'Algorithom', checked: false},
    ],
};

export const getters: GetterTree<State, any> = {
    todos: state => state.todos.filter(t => !t.checked),
    dones: state => state.todos.filter(t => t.checked)
};

export const mutations: MutationTree<State> = {
    addTodo(state, newTodo) {
        const copy = {
            ...newTodo
        };
        state.todos.push(copy);
    }
};

export const actions: ActionTree<tate, any> = {
    addTodoAsync(context, id) {
        fetch('https://jsonplaceholder.typicode.com/posts/'+id)
            .then(data => data.json())
            .then(item => {
                const todo: Todo = {
                    checked: false,
                    text: item.title
                }

                context.commit('addTodo', todo);
            })
    }
}

export default state;
复制代码

 

Add into root Store:

复制代码
import Vue from 'vue';
import Vuex from 'vuex';

import todos, {getters, mutations, actions} from './todos';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    ...todos,
  },
  getters,
  mutations,
  actions
});
复制代码

 

Using '@Action' inside component:

复制代码
<template>
<section>
    <h4>Todos</h4>
    <ul>
      <li v-for="todo in todos">{{ todo.text }}</li>
    </ul>
    <h4>Done</h4>
    <ul>
      <li v-for="todo in dones">{{ todo.text }}</li>
    </ul>
    <p>
      <label for="">
        Add todo:
        <input type="text" v-model="newTodo.text" @keyup.enter="addTodo(newTodo)">
      </label>
      <label for="">
        Add todo async:
<input type="text" v-model="id" @keyup.enter="addTodoAsync(id)">
      </label>

    </p>
</section>
</template>

<script lang="ts">
import {Component, Vue} from 'vue-property-decorator';
import {Action, State, Getter, Mutation} from 'vuex-class';
import {Todo} from '../types';

@Component({
})
export default class Todos extends Vue {
    @Getter todos: Todo[];
    @Getter dones: Todo[];

    @Mutation addTodo;
    @Action addTodoAsync;

    newTodo: Todo = {
      text: '',
      checked: false
    }

    id: string = '1';
}
</script>
复制代码

 

posted @   Zhentiw  阅读(428)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2017-04-28 [TypeScript] Find the repeated item in an array using TypeScript
2016-04-28 [AngularJS] angular-md-table for Angular material design
2016-04-28 [Angular 2] Using a Value from the Store in a Reducer
2016-04-28 [Angular 2] Using a Reducer to Change an Object's Property Inside an Array
点击右上角即可分享
微信分享提示