另一个属性中的引用元素属性(Reference element property within another property)

我试图访问动态属性( :class )中的属性( fieldType , value )

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

这会记录以下错误:

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.

我想它期望fieldType是一个数据属性。

如何实现,或者这是一种反模式?

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?

最满意答案

使用v-for填充值会将整个对象公开给模板语法

我假设你的对象系统,但它对不同的结构是通用的。

<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>

虽然老实说你不再需要value和fieldType属性,除非你在某处引用它们。

那将允许你使用

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) } }

所以div就像一个无线电选择。

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.

更多推荐