S
S
Speakermen2021-03-20 21:45:11
Vue.js
Speakermen, 2021-03-20 21:45:11

Why does TypeError: Cannot read property '0' of undefined occur?

I can’t understand in the console there is And when in html I want to turn the error TypeError: Cannot read property '0' of undefinedconsole.log(this.errors.title[0]);

<div v-if="errors.title" class="alert alert-danger">
                {{ errors.title[0] }}
            </div>


<template>
    <div>
        <form @submit.prevent="submit_form">
            Post title:
            <br/>
            <input type="text" class="form-control" v-model="fields.title">
            <div v-if="errors.title" class="alert alert-danger">
                {{ errors.title }}
            </div>
            Post text:
            <br/>
            <textarea rows="10" class="form-control" v-model="fields.post_text"></textarea>
            <br/>
            Category:
            <select class="form-control" v-model="fields.category_id">
                <option selected value="">-- choose category --</option>
                <option v-for="category in categories.data" :value="category.id" :key="category.id">
                    {{ category.name }}
                </option>
            </select>
            <br>
            <input type="submit" class="btn btn-primary" value="Save post"/>
        </form>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                categories: {},
                fields: {
                    title: '',
                    post_text: '',
                    category_id: ''
                },
                errors: {}
            }
        },

        mounted() {
            axios.get('/api/categories').then(response => {
                this.categories = response.data;
            });
        },

        methods: {
            submit_form() {
                axios.post('/api/posts', this.fields).then(response => {
                    this.$router.push('/');
                }).catch(error => {
                    if (error.response.status === 422) {
                        this.errors = error.response.data.errors;

                        console.log(this.errors.title[0]);
                    }
                });
            }
        }
    }
</script>

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question