console
var newww = new Vue({
'el': '#page',
data() {
return {
godSon: '',
nameArr: [
{value: '铭辉', key:'minghui', checked: true},
{value: '毅鹏', key:'yipeng', checked: true},
{value: '绍落', key:'shaoluo', checked: true},
{value: '建瀚', key:'jianhan', checked: true},
{value: '伟进', key:'weijin', checked: true},
],
newArr: [],
selectArr:[],
selectKeyArr:[],
totalGuy: '',
lastNum: null
}
},
methods:{
randomName(){
if(!this.totalGuy){
alert('请先选择人数和范围');
return false;
}
this.judgeNumber();
let filter = [];
this.nameArr.map(item =>{
if(item.checked){
filter.push(item)
}
})
this.newArr = filter;
let maxNum = filter.length;
let minNum = 0;
let a =parseInt(Math.random()*(maxNum-minNum+1)+minNum,10);
console.log('a',a);
console.log('filter',this.filter,a);
console.log('filter[a].key',filter[a]['key']);
for(let value of this.selectKeyArr){
if(value === filter[a]['key']){
this.randomName();
return false;
}else{
console.log(filter[a].value)
}
}
for(let i in filter){
if(this.lastNum && this.lastNum == a){
continue;
}
if(i == a){
this.judgeNumber()
this.godSon = filter[i].value;
this.selectArr.push(filter[i].value);
this.selectKeyArr.push(filter[i].key);
this.lastNum = a;
return false;
}
}
},
judgeNumber(){
if(this.selectArr.length === Number(this.totalGuy)){
alert('已超出数量范围,已停止选举');
return false;
}
},
checkInput(json){
console.log(json.key);
let arr = this.nameArr;
arr.map(arrItem => {
if(arrItem.key == json.key){
arrItem.checked = !json.checked
}
});
this.nameArr = arr
},
},
watch:{
'totalGuy'(newV,oldV){
if(newV !== oldV){
this.newArr = [];
this.godSon = ''
}
}
}
})
<div id="page">
<div v-for="item in nameArr">
<label :for="item.key" >
<input type="checkbox" :id="item.key" :name="item.value" :checked="item.checked" @click="checkInput(item)">
{{item.value}}
</label>
</div>
<div>天选之子人数: <input type="Number" v-model="totalGuy"></div>
天选之子总人数:
<div ><span v-for="item1 in selectArr">{{item1}},</span></div>
<div>
<button @click="randomName">点击</button>
天选之子:{{godSon}}
</div>
</div>