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

标签 vue.js vuex

对于这样的组件

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

相关文章:

vue.js - 如何使用 VueJS 路由器链接主动样式

vue.js - 如何在vue组件中使用vuex?

javascript - 页面刷新后 Vuex 状态在突变中为 null 而不是预定义对象

javascript - Vue 2 contentEditable with v-model

javascript - 为什么在这个 Vue 3 应用程序中无法将计算属性绑定(bind)为内联样式?

javascript - 由于 HTML 内容限制,标签 <slot> 不能出现在 <table> 内。它将被浏览器从 <table> 中提升出来

javascript - Vuex - 仅在 getter 上修改状态对象

vue.js - Vue中获取子组件的输入值

javascript - Vuex Action 是否必须修改或使用存储状态?

javascript - Eslint 和 VueJS 文件。抛出错误但不修复它们