2016-11-17 18 views
1

我想单独为每个输入激活一个类。我有两个输入绑定到相同的V模型和类。我有一个方法检查某些事情是否为真,如果为true,则启用绑定类。目前它可以在所有输入上启用该类。 (最终目标是在一个阵列中搜索多个输入一个元素,如果它匹配,类只激活该元素)如何为数组中的单个元素激活一个类? [Vue.js]

<input v-model="highlightTest" id="1" v-bind:class="{ active: active }" v-on:keyup="Highlighting"></input> 

<input v-model="highlightTest" id="2" v-bind:class="{ active: active }" v-on:keyup="Highlighting"></input> 

Highlighting: function() { 
    if (this.highlightTest != '') { 
    this.active = true; 
} 
else { 
this.active = false; 
} 
+0

我不太明白你正在尝试做的,但你永远无法为主动类一个单独的输入如果所有的输入都绑定到相同的类和相同的模型。你能更好地解释你想要完成什么? –

+0

感谢您的反馈安东尼奥。我可以展示过去为了获得更好的想法而使用jQuery所能做的一个例子。 目标是让用户输入生成的单词列表。 单词列表被放入列表中。 当该列表中的单词输入到输入区域时,它会单独突出显示。 我现在试图用vue来达到这个目的的问题是,一旦输入该单词就会抛出标志,该类下的所有单词都会激活。 下面是我的一些旧代码的例子。 https://jsfiddle.net/aydg436k/ – Pyreal

+0

您希望列表中的单词变为活动状态吗?还是输入您希望变为活动状态的单词?编辑:好吧,看到小提琴后我看到了。如果没有提供并首先接受答案,我会尽快回复您。 –

回答

1

如何:

<template> 
    <input v-for="(hi,index) of highlights" v-model="highlights[]" v-bind:class="{ active: highlights[index] }" v-on:keyup="highlighting(index)"></input> 
</template> 

<script> 
export default{ 
    data() { 
     return { 
      highlights: [] 
     }; 
    }, 
    created() { 
     this.$http.get('some/api').then(res => { 
      // map: convert 0,1 to false,true 
      this.highlights = res.json().map(h => h==1); 
     }); 
    }, 
    methods: { 
     highlighting(index) { 
      if (this.highlights[index]) { 
       // this.highlights[index] = false won't let vue detect the data change(thus no view change) 
       this.highlights.splice(index, 1, false); 
      } else { 
       this.highlights.splice(index, 1, true); 
      } 
     } 
    } 
} 
</script> 
0

这里有一种方法来做到这一点(对不起者均基于延迟)

HTML:

<div id="app"> 
     <p :class="{'active': activateWord(word)}" v-for="word in words">@{{ word }}</p> 
     <input type="text" v-model="inputText"> 

    </div> 

CSS:

.active { 
    color: red; 
} 

JS:

const app = new Vue({ 
    el: '#app', 
    data: { 
     inputText: '', 
     words: [ 
     'foo', 
     'bar' 
     ] 
    }, 
    methods: { 
     activateWord(word) { 
      return this.inputText === word 
     }, 
    }, 
}) 

here“SA小提琴

相关问题