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>

[Vuex] Perform Async Updates using Vuex Actions with TypeScript的更多相关文章

  1. Vuex结合 async/await 优雅的管理接口请求

    先看看 async/await 的语法 async 函数返回一个 Promise 对象 async 函数内部 return 返回的值.会成为 then 方法回调函数的参数. 1 2 3 4 async ...

  2. 详解Vuex常见问题、深入理解Vuex

    Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式.它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化. 状态?我把它理解为在data中的属性需要共 ...

  3. 浅读vuex源码,了解vuex基本原理

    极简版vuex代码 class KVuex { constructor (options) { this.state = options.state this.mutations = options. ...

  4. vuex 源码:深入 vuex 之辅助函数 mapState

    前言 当一个组件要获取多个 state 的时候,声明计算属性就会变得重复和冗余了.我们可以使用到辅助函数 mapState 来更快更简洁地生成计算属性. 所以我们得清楚,mapState 的作用就是帮 ...

  5. [Vue] Use Vue.js Watchers to Respond to Async Updates

    Use watchers to keep an eye on your data. Watchers are methods that are invoked when the specified a ...

  6. [Vue + TS] Watch for Changes in Vue Using the @Watch Decorator with TypeScript

    Vue watchers allow to perform async updates as a side effect of a property change. This lesson shows ...

  7. vuex所有核心概念完整解析State Getters Mutations Actions

    vuex是解决vue组件和组件件相互通信而存在的,vue理解起来稍微复杂但一旦看懂择即为好用 安装: npm install --save vuex 引入 import Vuex from 'vuex ...

  8. vuex 笔记

    Vuex 笔记 一个简单的状态管理 单一数据源: const sourceOfTruth = {} const vmA = new Vue({ data: sourceOfTruth }) const ...

  9. vuex 使用文档

    安装 直接下载CDN 引用 <script src="/path/to/vue.js"></script> <script src="/pa ...

随机推荐

  1. 解决背景图文字盖住html里面的dom元素

    width:100%; background: url('../images/res.jpg') no-repeat 0 0px; background-attachment:fixed; backg ...

  2. 使用Phar来打包发布PHP程序

    简单来说,Phar就是把Java界的jar概念移植到了PHP界. Phar可以将一组PHP文件进行打包,还可以创建默认执行的stub(或者叫做 bootstrap loader),Phar可以选择是否 ...

  3. 052 kafka对topic的增删改查操作

    一:create 1.开始使用命令 2.创建 bin/kafka-topics.sh --create --topic beifeng --zookeeper linux-hadoop01.ibeif ...

  4. day 68 django 之api操作 | jQueryset集合与对象

    我们的orm里面分为: jQueryset集合, 还有对象, 我们的jqueryset集合里面可以有多个对象,这句话的意思就是我们的对象是最小的单位,不可以再拆分了,我们的jQueryset集合就相当 ...

  5. SSL/TLS

    為 授权计算机为 SSL/TLS 安全通道建立信任关系. ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, e ...

  6. 电信项目java补充类

    一.DecimalFormat 1.概述 public class DecimalFormat extends NumberFormat DecimalFormat是格式为十进制数的NumberFor ...

  7. 20165220 Java第五周学习总结

    教材学习内容总结 1.try—catch语句:Java用try—catch语句来处理异常.将可能出现的异常操作放在try中,当try出现异常时,此部分立刻结束运行,转向执行catch部分.一个try- ...

  8. C++学习之 —— 输入输出

     案例:输入任意空格和数字,输出其中的数字之和. #include <iostream> using namespace std; int main() { ; cout << ...

  9. zabbix安装和配置

  10. Android视图动画集合AndoridViewAnimations

    Android视图动画集合AndoridViewAnimations Android视图动画是针对视图对象的动画效果,包括对象平移.旋转.缩放和渐变四种类型.通过组合这四种类型,可以创建出无数种动画效 ...