Home > front end >  Computed property referencing wrong 'this' when trying to add a class depending on the cha
Computed property referencing wrong 'this' when trying to add a class depending on the cha

Time:12-01

I just need some help identifying why I get an error on my computed property. The error is:

Error in render: "TypeError: Cannot read property 'length' of undefined"

I assume as I am looping through activeConnect.nodes when I reference this.node it does't know which one I am referring too? How do I fix my computed to do this correctly?

   <v-col
      v-for="(node, index) in activeConnect.nodes"
      :key="index"
    >
      <v-card
        flex
        @click="edit(node)"
      >
        <v-card-text
          :class="nameClass"
          text-no-wrap
          v-text="node.content"
        />
      </v-card>
    </v-col>

Computed:

  computed: {
    nameClass () {
      if (this.node.content.length > 4) {
        return 'name-small'
      }
      return 'name'
    }
  }

SCSS:

.name-small {
  font-size: 12px !important;
}

.name {
  font-size: 20px !important;
}

CodePudding user response:

There's no this.node, node is local name inside v-for. There are several options to address this.

nameClass can be a method that receives node as parameter.

A part of a template that depends on node value (v-card) can be moved to a separate component that receives node as a prop and can have nameClass computed.

A simple calculation like in nameClass can be moved to a template.

  • Related