<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>为指定书名添加颜色</title> <style> body{ font-family:微软雅黑 } .search input{ width:350px; height:30px; } .item{ width:350px; height:100px; line-height:100px; border-bottom:1px solid #999999; } .item img{ width:100px; float:left } .active{ height:100px; line-height:100px; color:#FF0000 } </style> <script src="js/vue.js"></script> </head> <body>> <div id="example"> <!-- 显示全部图书信息 --> <div> <div class="item" v-for="book in books"> <img v-bind:src="book.image"> <span v-bind:class="{active: book.active}" style="cursor: pointer" v-on:click="changeColor(book)">{{book.bookname}}</span> </div> </div> </div> <script type="text/javascript"> var vm = new Vue({ el:'#example', data:{ //定义图书信息数组 books : [ { bookname : '零基础学JavaScript', image : 'images/javascript.png', // active : false }, { bookname : '零基础学HTML5+CSS3', image : 'images/htmlcss.png', // active : false }, { bookname : 'JavaScript精彩编程200例', image : 'images/javascript200.png', // active : false }, { bookname : 'HTML5+CSS3精彩编程200例', image : 'images/htmlcss200.png', // active : false } ] }, created:function(){ for(let i=0;i<this.books.length;i++){ Vue.set(this.books[i],'active',false) } }, methods: { changeColor(book){ // 先把所有的书都变成黑色 for(let i = 0 ; i<this.books.length; i++){ this.books[i].active = false } // 再把单击的书变成黑色 book.active = true } } }) </script> </body> </html>