该节教程代码可经过npm start运行devServer,在http://localhost:8080/#/index查看效果vue
运行服务端请cd server,node server.js。node
文件内容为[{"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访问到它。git
代码示例:/lesson23/src/store/index.jsgithub
因为Mutations不接受异步函数,所以只能经过Actions来实现异步请求。 在Actions中添加一个异步Action:npm
actions: {
async readUsers ({commit}) {
let res = await fetch('http://localhost:8081/user.txt')
let users = await res.json()
commit('setUsers', users)
}
},
复制代码
在Mutations中经过setUsers接收并更新users数据:json
setUsers (state, users) {
state.users = users
}
复制代码
代码示例:/lesson23/src/components/Index.vuebash
在生命周期created中,发起一个异步Action获取数据:服务器
async created(){
await this.readUsers();
},
复制代码