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>
asked Jun 20, 2017 at 21:38
\$\endgroup\$

1 Answer 1

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.

answered Jun 25, 2017 at 0:35
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.