2

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

11
  • 1
    Add the code where you dispatch/commit data to events list. Commented Jul 13, 2020 at 22:35
  • can u try this? getters: { getEvent: (state) => { return state.event } } Commented Jul 13, 2020 at 22:55
  • you need to provide more info. could you please show your main.js? Commented Jul 13, 2020 at 22:57
  • @Nanfish, Add getEvents action for example Commented Jul 14, 2020 at 8:30
  • @KickButtowski, this does this code differ from mine in principle Commented Jul 14, 2020 at 8:31

2 Answers 2

2

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/', {
Sign up to request clarification or add additional context in comments.

Comments

0
  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.

6 Comments

What do you mean in last function(eventList) where you call catalogId
And you wrote a function "mounted" for get response from rest. How i can call(get name) function to post and update and delete(also mounted or how)
Sorry, I adited my answer (catalogId was from my code)
mounted() is the life cycle hook of vue component, you can call there any rest request you want, furthermore you can fetch data from any method you want, but not in action. the idea is that store is for saving data and not for all other logic.
in other words, you don't need to create functions inside mounted (separately for get, post...) and write them all in one heap?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.