gpt4 book ai didi

vue.js - 从 REST API 获取的 Vuex 渲染数据

转载 作者:搜寻专家 更新时间:2023-10-30 22:07:54 25 4
gpt4 key购买 nike

对于这样的组件

<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>

商店:

const store: any = new Vuex.Store({
state: {
firstSectionId: null
},
// actions,
// mutations
})

我在 getSectionId 操作中有一个 Web 请求,它异步获取数据并调用将在 state 中填充 firstSectionId 的突变。在初始呈现期间,firstSectionIdnull,并且我收到警告,指出在呈现 router-link 期间缺少必需的参数。

这里加上v-if="firstSectionId"就没有问题了。但一般来说,从服务器获取数据以显示的方法是什么?目前,我所有的组件都在渲染之前检查存储中是否存在数据,这是正常的还是有更好的方法来等待数据加载后再渲染?

最佳答案

异步获取数据的一种方法是在 vuex store actions 中使用 promise

Vue.http.get(API_URL)
.then((response) => {
//use response object
})
.catch((error) => {
console.log(error.statusText)
});

为了证明我向 this route 发出了请求.您可以看到响应应该是什么样子。让我们将响应对象保存在 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

您注意到提交后有 self.filteruser() 方法。那是关键时刻。在此之前,我们正在提交突变,这是同步操作,我们确信我们将在 store.state 中有我们的响应,可以在 filterUsers() 方法中使用 < em>(别忘了传递自己的参数)

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)
}
}
}

更好的方法(ES6 和 ES7)

异步编程的 ES6 Promises

//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);
});
});
}
}

ES7:异步/等待

要摆脱回调 hell ,并改进异步编程,请使用async 函数,您可以await promise 。代码看起来更容易理解(就像它是同步的),但代码对于浏览器来说不可读,因此您需要 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())
}
}

关于vue.js - 从 REST API 获取的 Vuex 渲染数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41609155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com