Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

238
Vistas
How do I fix substring not working in vue.js 3?

I'm new in vuejs, and I'm trying to fetch posts from a JSON file using the composition API, but I'm having a problem. After fetching post, too many texts are being displayed, which is what I don't want. I have tried to fix it using the following method:

<template>
    <div class="max-w-md bg-white rounded-xl shadow-md overflow-hidden md:max-w-2xl m-6" v-for="post in post" :key="post.id">
        <div class="md:flex">
            <div class="md:flex-shrink-0" >
            <img class="h-48 w-full object-cover md:h-full md:w-48" src="assets/store.jpg" alt="Man looking at item at a store">
            <div class="p-8">
            <div class="uppercase tracking-wide text-sm text-indigo-500 font-semibold">News</div>
            <router-link :to="{name: 'Details', params:{id: post.id}}"><strong>{{post.title}}</strong></router-link>
            <p class="mt-2 text-gray-500">{{snippet}}</p>
            </div>
        </div>
    </div>
</template>

<script>
import { computed } from 'vue'
export default {
    props:['post'],
    setup(props) {
        const snippet = computed(() => {
            return props.post.body.substring(0,100) + '...'
        }) 
        return{snippet}
    }
}
</script>

The problem here is that when I run this piece of code, I get an error that says:

TypeError: Cannot read properties of undefined (reading 'substring')

And I don't even know how to go about this at the moment. Could someone please help?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

We can handle the undefined error by checking the properties value.

const snippet = computed(() => {
    let body = ''
    if (props.post && props.post.body){
      body = props.post.body.substring(0,100) + '...'
    }
    return body
}) 
about 4 years ago · Juan Pablo Isaza Denunciar

0

props.post.body is undefined. It's better to debug why it's undefined. Nevertheless, if the undefined can be ignored you can use the following ES10 optional chaining operator.

props.post.body?.substring(0,100)

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda