最近在看vue實戰這本書,小白一個,啥也不懂.
看書很痛苦,最主要的是容易犯困,正好書上有個實戰的內容叫問卷調查,用自己的想法實現了單選題這一部分.
1.每頁顯示一個題,點擊上一題,下一題進行切換
2.單選題不同的選項有不同的分值,點擊時會記錄當前選項是多少分,存在一個數組中了.
3.單選題有標題和選項,所以數據需要是二維數組了,這個可以自己先練習一下.
4.需要用到v-for的雙層循環,我是模版套的ul
5.num表示當前的頁數,index則是數組的大小,只顯示頁數和index相等的,所以就實現了每頁只顯示一個題的功能
<!DOCTYPE html> <htm> <head> <script src="vue.min.js"></script> </head> <body> <div id="app"> <template v-for="(book,index) in books"> <div v-if="num===index"> <p>{{index+1}}-{{book.title}}</p> <ul> <li v-for="(b,index) in book.content" @click="choose(index)">{{b.title}}</li> </ul> <p>-----------------------------------------------</p> </div> </template> <button @click="prex()">上一題</button> <button @click="next()">下一題</button> <p>{{num}}</p> <p>{{books.length}}</p> <p>本題得分: {{fen}}</p> </div> </body> <script> var app=new Vue({ el:'#app', data:{ num:0, fen:[], books:[ { title:'邏輯思維', content:[ { title:'中等偏上', fen:6 }, { title:'中等水平', fen:8 }, { title:'低水平', fen:2 } ] }, { title:'計划能力', content:[ { title:'選項A', fen:8 }, { title:'選項B', fen:15 } ] }, { title:'執行能力', content:[ { title:'選項A', fen:8 }, { title:'選項B', fen:15 }, { title:'選項c', fen:15 } ] } ], }, methods:{ next:function(){ if (this.num<this.books.length-1){ if (this.fen[this.num]>0){ this.num+=1; } } }, prex:function(){ if(this.num===0) { this.num=0; }else{ this.num-=1; } }, choose:function(index){ this.fen[this.num]=this.books[this.num].content[index].fen; } } }) </script> </htm>
代碼寫的很惡心,書只看到組件詳解這一章,沒有使用CSS,所以最終的效果如下圖