I'm trying to set up Vuex in my Vue app.
app.js
require('./bootstrap');
window.Vue = require('vue').default;
import Vuex from "vuex";
Vue.use(Vuex);
import storeData from "./store";
const store = new Vuex.Store(
storeData
)
Vue.component('home', require('./components/Home.vue').default);
const app = new Vue({
el: '#app',
store
});
store.js
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export const state = {
members: [],
};
export const getters = {
members: state => () => {
return state.members;
}
};
export const actions = {
async getMembers({ commit, state, dispatch }){
const res = await this.$axios.get('getMembers');
const { data } = await res;
commit('setMembers', data);
}
};
export const mutations = {
setMembers(state, members){
state.members = members;
},
};
export default new Vuex.Store({
state,
getters,
actions,
mutations
});
Home.vue
<template>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Home</div>
<div class="card-body">
{{ members }}
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import { mapGetters, mapActions, mapMutations } from "vuex";
export default {
mounted() {
this.getMembers();
},
computed: {
...mapGetters({
members: 'members'
})
},
methods: {
...mapActions({
getMembers: 'getMembers'
})
}
}
</script>
The homepage is showing the "members" getter with on issues. I see it in developer tools as an empty array and if I set it to anything else it will show it. However it is not detecting the actions or mutations if I try to make a mutation. The action for example says: "[vuex] unknown action type: getMembers" Any idea what may be causing this?
The store is initialized twice with new Vuex.Store
, the constructor is provided with store instance the second time, this results in a bug.
It's store that is exported from store.js, not store data .
It can be:
const store = new Vuex.Store({
state,
getters,
actions,
mutations
});
export default store;
Then it's clear that it's store instance that is exported from store.js.
Vue.use(Vuex)
is also called twice, this likely won't cause problems except a warning because Vue plugins usually contain a safeguard against multiple initialization. store.js doesn't need to contain it, it's common to initialize plugins in application entry point.
This is a potential mistake:
require('./bootstrap');
window.Vue = require('vue').default;
import Vuex from "vuex";
...
Imports are hoisted according to specs, this behaviour is setup-dependent but it shouldn't be expected that this code will be evaluated in this order.
Needs to be:
import './bootstrap';
import Vue from "vue";
import Vuex from "vuex";
import store from "./store";
window.Vue = Vue;
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.