Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vue教程23:Vuex异步Action #24

Open
chencl1986 opened this issue Mar 18, 2019 · 0 comments
Open

Vue教程23:Vuex异步Action #24

chencl1986 opened this issue Mar 18, 2019 · 0 comments

Comments

@chencl1986
Copy link
Owner

阅读更多系列文章请访问我的GitHub博客,示例代码请访问这里

该节教程代码可通过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();
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant