Vue教程23:Vuex异步Action

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chencl1986/article/details/85567465

示例代码请访问我的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();
},

猜你喜欢

转载自blog.csdn.net/chencl1986/article/details/85567465