Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

242
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda