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