2
\$\begingroup\$

I am using the following to output a thumbnail with text. It works fine but I don't like having the use a conditional to check every prop before outputting.

E.g. this.post.user.name would indicate "cannot read property of null". Some of the values coming from the database would be null.

Whats the standard procedure to do this?

<template>
    <div class="col-md-3">
        <div class="thumbnail">
            <a :href="src">
                <img :src="src">
            </a>
            <div class="caption">
                <h4>{{ post.make }}</h4>
                <h4>{{ post.model }}</h4>
                <h4>{{ userName }}</h4>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        props:{
            post:{
                type: Object,
                required: true
            }
        },
        data() {
            return {
                src:'',
                make: '',
                model: '',
                userName: ''
            }
        },
        mounted(){
            if (this.post.make !== null) {
                this.make = this.post.make
            };
            if (this.post.model !== null) {
                this.model = this.post.model
            };
            if (this.post.user !== null) {
                this.userName = this.post.user.name;
            }
        }
    }
</script>
\$\endgroup\$
1
\$\begingroup\$

By using v-if I was able to come up with a solution I am comfortable with.

<template>
    <div class="col-md-3">
        <div class="thumbnail">
            <a :href="src">
                <img :src="src">
            </a>
            <div class="caption">
                <h4 v-if="post.make">{{ post.make }}</h4>
                <h4 v-if="post.model">{{ post.model }}</h4>
                <h4 v-if="post.price" style="color:red;">{{ post.price }}</h4>
                <h4 v-if="post.user">{{ post.user.name }}</h4>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        props:{
            post:{
                type: Object,
                required: true
            }
        },
        data() {
            return {
                src:''
            }
        },
        mounted(){
            if (this.post.photos == 0 || this.post.photos === null) {
                return this.src = '/images/post-thumbnail.png'
            };
            this.src = '/storage/' + this.post.photos[0].name;
        }
    }
</script>

I also considered not allowing null in the database so I would not have to check for it but that needed some special attention.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.