我使用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()
为all buttonOptions
返回false
,那么将.active类添加到第一个按钮的最佳方法是什么?请注意,buttonOptions
是一个道具。
发布于 2018-06-09 04:09:25
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
}
}
});
.active {
background: #f00;
}
<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>
我不知道isActiveButton
方法是做什么的,所以我只能即兴发挥作用:它会检查字符串是否大写。
实现该功能的是计算属性shouldFirstBeActive
,如果buttonOptions
数组中的所有项都未通过isActiveButton
方法,则该属性将返回true
:
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
}
}
});
.active {
background: #f00;
}
<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>
发布于 2018-06-09 03:12:23
在isActiveButton为true并将this.buttonOptions作为参数的情况下,使用过滤索引的计算
https://stackoverflow.com/questions/50766775
复制相似问题