Vue教程23:Vuex异步Action

本文介绍如何在Vue项目中使用Vuex的Actions处理异步请求,包括读取本地服务器数据并更新状态的具体步骤。通过示例代码展示了如何创建异步Action、在组件中调用以及在store中定义Mutations来响应异步操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

示例代码请访问我的GitHub:
https://github.com/chencl1986/vue-tutorial

该节教程代码可通过npm start运行devServer,在http://localhost:8080/#/index查看效果

运行服务端请cd server,node server.js。

创建一个测试数据文件user.txt

文件内容为[{“id”:3,“name”:“lee”,“age”:18,“online”:true},{“id”:5,“name”:“zhangsan”,“age”:22,“online”:false},{“id”:11,“name”:“lisi”,“age”:25,“online”:true}]。
用于输出一个user列表。
通过cd server,node server.js启动服务器,就可以在http://localhost:8081/user.txt访问到它。

添加异步Action

代码示例:/lesson23/src/store/index.js

由于Mutations不接受异步函数,因此只能通过Actions来实现异步请求。
在Actions中添加一个异步Action:

actions: {
  async readUsers ({commit}) {
    let res = await fetch('http://localhost:8081/user.txt')
    let users = await res.json()

    commit('setUsers', users)
  }
},

在Mutations中通过setUsers接收并更新users数据:

setUsers (state, users) {
  state.users = users
}

发起异步Action

代码示例:/lesson23/src/components/Index.vue

在生命周期created中,发起一个异步Action获取数据:

async created(){
  await this.readUsers();
},
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值