softcode
softcode

Reputation: 4648

Reference element property within another property

I am trying to access properties (fieldType, value) within an dynamic property (:class)

<div fieldType="favoriteSports" 
     @click="update_favorite_sports" 
     value="Soccer"
     :class="{selected: sportsForm[fieldType].indexOf(value) != -1 }">
     Soccer
</div>

This logs the following error:

Property or method "fieldType" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.

I suppose it is expecting fieldType to be a data property.

How can this be achieved, or is this an anti-pattern?

Upvotes: 0

Views: 71

Answers (1)

Justin MacArthur
Justin MacArthur

Reputation: 4050

Using a v-for to fill values exposes the entire object to the template syntax

I'm assuming your object system but it's universal to different structures.

<div
    v-for="sport in sports"
    :fieldType="sport.type"
    @click="update_favorite_sports(sport)" 
    :value="sport.name"
    :class="{selected: sportsForm[sport.type].indexOf(sport.name) != -1 }"
>
    Soccer
</div>

Though honestly you no longer need the value and fieldType properties unless you're referencing them somewhere.

That will allow you to use

methods: {
    update_favorite_sports (sport) {
        // Whatever your code is guessing something like
        let index = this.sportsForm[sport.type].indexOf(sport.name)
        if(index >= 0) {
            this.sportsForm[sport.type].splice(index, 1)
            return
        }
        this.sportsForm[sport.type].push(sport.name)
    }
}

So that the div acts like a radio select.

Upvotes: 1

Related Questions