2
votes

There is a Form component.vue, which takes the event object from getter and substitutes it in v-model:

<template>
    <form @submit.prevent="submitForm">
        <div class="form-group row">
            <div class="col-10 d-flex">
                <input type="" class="title form-control" v-model="getEvent.title" placeholder="Название">
                <input type="" class="content form-control" v-model="getEvent.content" placeholder="Содержание">
                <input type="" class="event_date form-control" v-model="getEvent.event_date" placeholder="Дата">
                <input type="" class="email form-control" v-model="getEvent.email" placeholder="Email">
            </div>
            <div class="d-flex flex-column">
                <button class="btn btn-success mt-auto" >Создать</button>
            </div>
        </div>
    </form>
</template>

<script>
import { mapGetters, mapActions } from "vuex"

export default {
    computed: mapGetters(['getEvent']),
    methods: mapActions(['submitForm'])
}

However, vue returns an error stating that getter undefined. store/index.js:

import Vue from 'vue';
import Vuex from 'vuex';


Vue.use(Vuex);

Date.prototype.getWeek = function () {
    var onejan = new Date(this.getFullYear(), 0, 1);
    var today = new Date(this.getFullYear(), this.getMonth(), this.getDate());
    var dayOfYear = ((today - onejan + 86400000) / 86400000);
    return Math.ceil(dayOfYear / 7)
}

export const store = new Vuex.Store({
    actions: {
        async getEvents(context) {
            var response = await fetch('http://127.0.0.1:8000/rest/');
            var data = await response.json()
            context('getEvents', data)
        },
        async createEvent(context) {
            await this.getEvents();
            await fetch('http://127.0.0.1:8000/rest/', {
                method: 'post',
                headers: {
                    'content-type': 'application/json'
                },
                body: JSON.stringify({ event: context.state.event })
            });
            await this.getEvents();
            context.commit('createEvent', context.state.event)
        },
        async editEvent(context) {
            await this.getEvents();
            await fetch(`http://127.0.0.1:8000/rest/${context.state.event.id}/`, {
                method: 'put',
                headers: {
                    'content-type': 'application/json'
                },
                body: JSON.stringify({ event: context.state.event })
            });
            await this.getEvents();
            context.state.event = {};
        },
        async deleteEvent(context) {
            await this.getEvents();
            await fetch(`http://127.0.0.1:8000/rest/${context.state.event.id}/`, {
                method: 'delete',
                headers: {
                    'content-type': 'application/json'
                },
                body: JSON.stringify({ event: context.state.event })
            });
            await this.getEvents();
        },


        submitForm(context) {
            if (context.state.event.id === undefined) {
                this.createEvent();
            } else {
                this.editEvent();
            }
        },


        isMonthEqualNow(object) {
            var event_date = new Date(object.event_date)
            var date_now = new Date()
            return event_date.getMonth() === date_now.getMonth()
        },
        isWeekEqualNow(object) {
            var event_date = new Date(object.event_date)
            var date_now = new Date()
            return event_date.getWeek() === date_now.getWeek()
        },
        isDayEqualNow(object) {
            var event_date = new Date(object.event_date)
            var date_now = new Date()
            return event_date.getDate() === date_now.getDate()
        },
        eventsByFilters(context) {
            var events = context.state.events
            if (context.state.search === '' && context.state.selected) {
                switch (context.state.selected) {
                    case 'month':
                        return events.filter(item => this.isMonthEqualNow(item))
                    case 'week':
                        return events.filter(item => this.isMonthEqualNow(item) && this.isWeekEqualNow(item))
                    case 'day':
                        return events.filter(item => this.isMonthEqualNow(item) && this.isWeekEqualNow(item)
                            && this.isDayEqualNow(item))
                    default:
                        return events
                }
            } else {
                events.filter(item => item.title.indexOf(context.state.search) !== -1)
            }
        }

    },
    mutations: {
        setEvents(state,events){
            state.events = events
        },
        createEvent(state, event){
            state.events.push(event)
        }
    },
    state: {
        events: [],
        event: {},
        selected: '',
        search: ''
    },
    getters: {
        eventsByFilters(state) {
            return state.events
        },
        getSearch(state){
            return state.search
        },
        getSelected(state){
            return state.selected
        },
        getEvent(state) {
            return state.event
        }
    },
});

And also i have warning(warning in ./src/main.js

"export 'default' (imported as 'store') was not found in './store')

main.js

import Vue from 'vue'
import App from './App.vue'
import  store  from './store';

Vue.config.productionTip = false


new Vue({
  render: h => h(App),
  store
}).$mount('#app')

And the components themselves are not output

2
Add the code where you dispatch/commit data to events list.Nan fish
can u try this? getters: { getEvent: (state) => { return state.event } }Kick Buttowski
you need to provide more info. could you please show your main.js?Kick Buttowski
@Nanfish, Add getEvents action for exampleМарсель Абдуллин
@KickButtowski, this does this code differ from mine in principleМарсель Абдуллин

2 Answers

2
votes

The only issue, I have seen is your store is not exporting any default

export const store = new Vuex.Store(...

yet, your main.js uses to import the default

import store from 'src/store'

so use the following and hope your issue gets solved

import { store } from './store';

please check these links

  1. export-const-vs-export-default-in-es6

  2. named-export-vs-default-export-in-es6

One point to suggests

in the following lines, I do not think you need to use await for this.getEvents() because it has already used await inside its action.

for example,

    await this.getEvents();
    await fetch('http://127.0.0.1:8000/rest/', {
0
votes
  1. action is for commit data to mutation and in mutation you have to set data to state.
  2. You should not fetch data in action, instead call it from component, in mounted() or something.

an example:

export default {
    mounted() {
        var response = await fetch('http://127.0.0.1:8000/rest/');
        var data = await response.json()
        this.$store.dispatch("eventsList", data);
    }
}

and in store.js:

 actions: {
    eventsList({commit}, data) {
        commit('eventsList', data)
    }
 },
 mutations: {
    eventsList(state, data) {
        state.events= data
    },
 }

dispatch calls action -> commit calls mutation => in mutation set the data directly to state.