【问题标题】:Vuex problem. this.$store.dispatch(...) working, although ...mapAction do notVuex 问题。 this.$store.dispatch(...) 工作,虽然 ...mapAction 没有
【发布时间】:2020-11-01 13:44:09
【问题描述】:

我在从 vuex 调度 Actions 时遇到问题,我不知道为什么,但是 ...mapActions 不会触发对 Jsonplaceholder 的请求。但是this.$store.dispatch返回所有10个用户没有任何问题,所以这里有两个文件的脚本,home.vue页面和store.js:

首页:

<script>
  import { mapGetters, mapActions } from "vuex";
  export default {
    name: "Home",
    created() {
      // this.$store.dispatch('fetchUsers')
      console.log(this.$store);
    },
    computed: {
      ...mapGetters(["getUsers"])
    },
    methods: {
      ...mapActions(["fetchUsers"]),
      increment() {
        this.$store.commit("increment");
        console.log(this.$store.state.count);
      }
    }
  };
</script>

商店:

const store = new Vuex.Store({
  state: {
    count: 0,
    users: []
  },
  getters: {
    getUsers(state) {
      return state.users;
    }
  },
  mutations: {
    increment(state) {
      state.count++;
    },
    setUsers(state, users) {
      console.log(state, users);
      state.users = users;
    }
  },
  actions: {
    fetchUsers({ commit }) {
      return new Promise(resolve => {
        fetch("https://jsonplaceholder.typicode.com/users")
          .then(response => {
            return response.json();
          })
          .then(result => {
            console.log(result);
            commit("setUsers", result);
            return resolve;
          })
          .catch(error => {
            console.log(error.statusText);
          });
      });
    },
    incrementUsers({ commit }) {
      commit("fetchUsers");
    }
  }
});

【问题讨论】:

  • 有几件事情我发现做得不对,无论如何,让我们弄清楚,在 Skype 上联系我:syed_haroon

标签: javascript vue.js vuex store


【解决方案1】:

当您在这里使用mapGettersmapActions 时:

import {mapGetters, mapActions} from 'vuex'

更简单的方法是:

created() {
  this.fetchUsers()
  console.log(this.getUsers)
},
computed: {
  ...mapGetters(['getUsers'])
},
methods: {
  ...mapActions(['fetchUsers']),
}

此外,以防万一您喜欢使用名称间距,请遵循以下答案: https://stackoverflow.com/a/55269592/1292050

【讨论】:

  • 发生这种情况的一个非常常见的情况是有人将..mapActions 放在他们的计算属性而不是他们的方法中。 mapActions 是函数 - 因此它们进入方法! mapStatemapGetters 进入计算!
猜你喜欢
  • 1970-01-01
  • 2020-01-18
  • 2017-08-19
  • 1970-01-01
  • 2019-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多