对于这样的组件
<template>
<div>
<router-link :to="{name:'section', params: { sectionId: firstSectionId }}">Start</router-link>
</div>
</template>
<script lang="ts">
import { mapActions } from "vuex"
export default {
mounted() {
this.getSectionId()
},
computed: {
firstSectionId() {
return this.$store.state.firstSectionId
}
},
methods: mapActions(["getSectionId"])
}
</script>
Run Code Online (Sandbox Code Playgroud)
商店:
const store: any = new Vuex.Store({
state: {
firstSectionId: null
},
// actions,
// mutations
})
Run Code Online (Sandbox Code Playgroud)
我在一个Web请求getSectionId
的行动,并会以异步方式获取数据并调用的突变,将填补firstSectionId
中state
.在初始渲染firstSectionId
过程中null
,我得到的警告是在渲染过程中缺少必需的参数router-link
.
这里添加不是问题v-if="firstSectionId"
.但一般来说,从服务器获取数据的方法是什么?目前我的所有组件都在检查呈现前是否存在数据,是否正常或是否有更好的方法等待数据在呈现之前加载?
t_d*_*m93 56
异步获取数据的一种方法是在vuex存储操作中使用promise.
Vue.http.get(API_URL)
.then((response) => {
//use response object
})
.catch((error) => {
console.log(error.statusText)
});
Run Code Online (Sandbox Code Playgroud)
为了证明我向这条路线提出要求.您可以看到响应应该如何.让我们在state.users数组中保存响应对象.
store.js
const store = new Vuex.Store({
state: {
users: []
},
mutations: {
FETCH_USERS(state, users) {
state.users = users
}
},
actions: {
fetchUsers({ commit }, { self }) {
Vue.http.get("https://jsonplaceholder.typicode.com/users")
.then((response) => {
commit("FETCH_USERS", response.body);
self.filterUsers();
})
.catch((error) => {
console.log(error.statusText)
});
}
}
})
export default store
Run Code Online (Sandbox Code Playgroud)
您注意到self.filteruser()
提交后有方法.那是至关重要的时刻.在此之前我们提交了一个变异,这是同步操作,我们确信我们将在store.state中获得可以在filterUsers()
方法中使用的响应(不要忘记通过self parm)
Users.vue
import store from "../store/store"
export default {
name: 'users',
created() {
this.$store.dispatch("fetchUsers", { self: this })
},
methods:{
filterUsers() {
//do something with users
console.log("Users--->",this.$store.state.users)
}
}
}
Run Code Online (Sandbox Code Playgroud)
ES6承诺异步编程
//User.vue
created() {
this.$store.dispatch("fetchUser").then(() => {
console.log("This would be printed after dispatch!!")
})
}
//store.js
actions: {
fetchUser({ commit }) {
return new Promise((resolve, reject) => {
Vue.http.get("https://jsonplaceholder.typicode.com/users")
.then((response) => {
commit("FETCH_USERS", response.body);
resolve();
})
.catch((error) => {
console.log(error.statusText);
});
});
}
}
Run Code Online (Sandbox Code Playgroud)
ES7:异步/等待
为了摆脱回调地狱,并改进异步编程使用async
功能,你可以await
承诺.代码看起来更容易遵循(就像它是同步的),但代码对于浏览器是不可读的,因此您需要使用Babel转换器来运行它.
actions: {
async actionA ({ commit }) {
commit('gotData', await getData())
},
async actionB ({ dispatch, commit }) {
await dispatch('actionA') // wait for actionA to finish
commit('gotOtherData', await getOtherData())
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
32129 次 |
最近记录: |