vue編寫實現考試模塊答題功能單選多選

需求: 單選多選判斷題。
由於單選和判斷性質一樣,這裏我就只寫下單選和多選題;
大概實現這樣的效果:
在這裏插入圖片描述
返回的數據格式大概是這樣:

[
 {
    "id": "0f78fab04fab11eaabe802429c67f104",
     "answeroptions": [
         "A.選項一",
         "B.選項二",
         "C.選項三",
         "D.選項四"
     ],
     "questioncontent": "請選擇下列正確選項"
  },
  {
    "id": "0f78fab04fab11eaabe802429c67f105",
     "answeroptions": [
         "A.選項一",
         "B.選項二",
         "C.選項三",
         "D.選項四"
     ],
     "questioncontent": "請選擇下列正確選項"
  },
]

單選題:

<div class="e-content" v-for="(item,index) in singleChoiceInfo" :key="item.relationsubject">
    <div class="e-top">
        {{index+1}}{{item.questioncontent}}
    </div>
    <div class="e-cent">
        <div class="" v-for="(ite,ind) in item.answeroptions" :key="ind"
        :class="{
            btns:container1[index] == ind
        }">
            <div class="e-cent1" @click="check1(ite,ind,index)">{{ite}}</div>
        </div>
    </div>
</div>
methods:{
	check1: function(itm,ind,index){
     	this.$set(this.container1,index,ind)
    },
}

check1是個點擊事件,v-for循環的singleChoiceInfo是單選題的數據來源,也就是上面的展示數據,container1是個初始化定義的空數組(用來接收點擊後的參數),每次點擊使用$set方法修改container1,使得視圖可以及時刷新。
多選題:

<div class="e-content" v-for="(item,index) in mutipleChoiceInfo" :key="item.relationsubject">
    <div class="e-top">
       {{index+1}}{{item.questioncontent}}
    </div>
    <div class="e-cent" v-if="container2.length>0">
        <div class="" v-for="(ite,ind) in item.answeroptions" :key="ind"
        :class="{
            btns:container2[index].indexOf(ind)>-1
        }"
        >
            <div class="e-cent1" @click="chenk2(ite,ind,index)">{{ite}}</div>
        </div>
    </div>
</div>
methods:{
	chenk2: function(itm,ind,index){
       let arrIndex = this.container2[index].indexOf(ind)
       if(arrIndex>-1){
            this.container2[index].splice(arrIndex,1)
        }else{
            this.container2[index].push(ind)
        }
	},
	transformation: function(){
       for(let i=0,mutI = this.mutipleChoiceInfo.length;i<mutI;++i){
            this.container2.push([])
        }
    },
},
mounted(){
   this.transformation()
}

同上check2是個點擊事件,v-for循環的mutipleChoiceInfo是多選題的數據來源,也就是上面的展示數據,container2是個初始化定義的空數組(用來接收點擊後的參數),我在頁面加載完之後會調用一個transformation()方法,往container2中push進和數據源length相等的空數組,這樣方便下一步點擊事件時修改,然後通過indexOf()方法,點擊事件發生時,判斷點擊的這個選項是否存在於對應的數組中,不存在則加入,存在則刪除。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章