Vuex 问题。 this.$store.dispatch(...) 工作,虽然 ...mapAction 不
Vuex problem. this.$store.dispatch(...) working, although ...mapAction do not
我在从 vuex 调度 Actions 时遇到问题,我不知道为什么,但是...mapActions 不会触发对 Jsonplaceholder 的请求。但是 this.$store.dispatch
return 所有 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");
}
}
});
因为您在这里使用 mapGetters
和 mapActions
:
import {mapGetters, mapActions} from 'vuex'
更简单的方法是:
created() {
this.fetchUsers()
console.log(this.getUsers)
},
computed: {
...mapGetters(['getUsers'])
},
methods: {
...mapActions(['fetchUsers']),
}
此外,以防万一,如果您想使用名称间距,请遵循以下答案:
我在从 vuex 调度 Actions 时遇到问题,我不知道为什么,但是...mapActions 不会触发对 Jsonplaceholder 的请求。但是 this.$store.dispatch
return 所有 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");
}
}
});
因为您在这里使用 mapGetters
和 mapActions
:
import {mapGetters, mapActions} from 'vuex'
更简单的方法是:
created() {
this.fetchUsers()
console.log(this.getUsers)
},
computed: {
...mapGetters(['getUsers'])
},
methods: {
...mapActions(['fetchUsers']),
}
此外,以防万一,如果您想使用名称间距,请遵循以下答案: