您的位置:首页 > 产品设计 > UI/UE

vue简单class切换

2018-02-01 18:35 211 查看
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<style>
.text-success {
color: red;
}
</style>
</head>
<body>
<div id="app">
<ol>
<!--循环options选项-->
<li v-for="(option,index) in options">
<!--三目运算,判断是否显示class='text-success'-->
<p v-bind:class="[option.active ? 'text-success' : '']" v-on:click="addClass(index)">Text:{{option.key}}--Value:{{option.price}}--index:{{index}}--option:{{option.active}}</p>
</li>
</ol>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
/*选项*/
options: [
/*默认第一个显示Class*/
{key: '苹果', price: '20', active: true},
{key: '香蕉', price: '30', active: false},
{key: '鸭梨', price: '40', active: false},
{key: '草莓', price: '50', active: false}
],
/*变量保存上一次点击的index值*/
upIndex: ''
},
methods: {
addClass: function (index) {
/*移除默认显示的class*/
this.options[0].active = false;
/*判断upIndex是否为空*/
if (this.upIndex !== '') {
/*判断upIndex是否等于当前点击的index*/
if (this.upIndex !== index) {
/*当前点击的 index 的怕 P 元素显示class*/
this.options[index].active = true;
/*移除上一次点击的 P 元素的*/
this.options[this.upIndex].active = false;
/*保存index*/
this.upIndex = index;
}
} else {
/*当前点击的index的class显示*/
this.options[index].active = true;
/*保存upIndex*/
this.upIndex = index;
}
}
}
})
</script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  vue