-
示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> span.active{ color:red; } </style> </head> <body> <div id="app"> <div> <span @click="handlerClick(index)" v-for = "(category,index) in categoryList" :key="category.id" :class="{active:index==currentIndex}"> <!--綁定屬性--> {{ category.name }} </span> </div> </div> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> <script src='./vue.js'></script> <script> let vm = new Vue({ // 聲明變量 實例化一個對象vm(指的是vue的實例) el: "#app", //綁定根元素 //數據屬性 data(){ //這里有obsever //返回的數據跟后端數據庫里的有關,如果是動態的數據,存的是數據結構 return {categoryList:[],currentIndex:0} }, methods:{ handlerClick(i){this.currentIndex=i;} }, created(){ $.ajax({ //請求后端數據 **** url:"https://www.luffycity.com/api/v1/course_sub/category/list/", type:"get", // success:function(data){ //后端數據渲染回來 success:(data)=>{ //data 一般是從后端返回給前端的 console.log(data); //Object //data:(6) [{…}, {…}, {…}, {…}, {…}, {…}, __ob__: Observer] //error_no:0 //proto__:Object if (data.error_no === 0){ var data=data.data; let obj={ id:0, name:"全部", category:"0" } this.categoryList = data; this.categoryList.unshift(obj) //把data賦值給categoryList console.log(this)//拿到的是一個ajax對象, // 所以把上面的匿名函數改成箭頭函數 //改成箭頭函數之后得到的是vue對象 this.categoryList=data; } }, error:function(err){ console.log(err); } }) } }) </script> </body> </html>