我使用v-for
创建按钮。如果isActiveButton()
返回true,我会添加.active类:
<button
v-for="(text, index) in this.buttonOptions"
class="btn"
:class="{active: isActiveButton(text)}"
:value='text'
@mousedown.prevent @click="some_method">
{{text}}
</button>
如果isActive()
为所有 false
返回buttonOptions
,将.active类添加到第一个按钮的最佳方法是什么?请注意,buttonOptions
是道具。
答案 0 :(得分:2)
A Computed Property将是最佳选择!
var app = new Vue({
el: '#app',
data: {
buttonOptions: ['button1', 'button2', 'button3', 'button4']
},
methods: {
isActiveButton: function (text) {
return (text === text.toUpperCase());
},
some_method: function() {
console.log('Button clicked')
}
},
computed: {
shouldFirstBeActive: function () {
return (this.buttonOptions.filter(el => this.isActiveButton(el))).length === 0
}
}
});
&#13;
.active {
background: #f00;
}
&#13;
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
<section>
<button
v-for="(text, index) in buttonOptions"
class="btn"
:class="{active: isActiveButton(text) || (shouldFirstBeActive && index === 0)}"
:value='text'
@mousedown.prevent @click="some_method">
{{text}}
</button>
</section>
</div>
&#13;
我不知道方法isActiveButton
做了什么,所以我不得不即兴发挥:它检查字符串是否为大写。
如果shouldFirstBeActive
数组中的所有项都未通过true
方法,则返回buttonOptions
的计算属性isActiveButton
的作用是什么:
return (this.buttonOptions.filter(el => this.isActiveButton(el))).length === 0
例如,如果您将button2
更改为BUTTON2,那么isActiveButton
会返回该项目的true
,这会将shouldFirstBeActive
计算的属性呈现为false
var app = new Vue({
el: '#app',
data: {
buttonOptions: ['button1', 'BUTTON2', 'button3', 'button4']
},
methods: {
isActiveButton: function (text) {
return (text === text.toUpperCase());
},
some_method: function() {
console.log('Button clicked')
}
},
computed: {
shouldFirstBeActive: function () {
return (this.buttonOptions.filter(el => this.isActiveButton(el))).length === 0
}
}
});
&#13;
.active {
background: #f00;
}
&#13;
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
<section>
<button
v-for="(text, index) in buttonOptions"
class="btn"
:class="{active: isActiveButton(text) || (shouldFirstBeActive && index === 0)}"
:value='text'
@mousedown.prevent @click="some_method">
{{text}}
</button>
</section>
</div>
&#13;
答案 1 :(得分:1)
使用计算过滤this.buttonOptions,其中isActiveButton为true,并将index作为参数