<!DOCTYPE html>
<html>
<head>
<title>shuffles</title>
<script src="https://unpkg.com/vue"></script>
<style>
.container {
display: flex;
flex-wrap: wrap;
width: 238px;
margin-top: 10px;
}
.cell {
display: flex;
justify-content: space-around;
align-items: center;
width: 25px;
height: 25px;
border: 1px solid #aaa;
margin-right: -1px;
margin-bottom: -1px;
}
.cell:nth-child(3n) {
margin-right: 0;
}
.cell:nth-child(27n) {
margin-bottom: 0;
}
.cell-move {
transition: transform 1s;
}
</style>
</head>
<body>
<div id="sudoku-demo" class="demo">
<button @click="shuffles">
Shuffle
</button>
<transition-group name="cell" tag="div" class="container">
<div v-for="cell in cells" :key="cell.id" class="cell">
{{ cell.number }}
</div>
</transition-group>
</div>
<script>
new Vue({
el: "#sudoku-demo",
data: {
cells: []
},
methods: {
shuffles: function () {
this.shuffle(this.cells);
},
shuffle(data) {
//第一种方法loadsh.js中shuffle的实现方式: 新复制一个数组,指向不同,再重新赋值给this.cells
// this.cells = this.randowPostions(this.copyArr(data))
//第二种方法自己实现: 因为改变数组中某一个值时,视图是不会刷新的 所以强制刷新
return this.randowPostion(data)
},
copyArr(array,targetArr){ //复制数组
var index = -1,
length = array.length;
targetArr || (targetArr = Array(length));
while (++index < length) {
targetArr[index] = array[index];
}
return targetArr;
},
randowPostion(tempArr,size){
this.randowPostions(tempArr);
this.cells = tempArr;
this.$forceUpdate(); //强制刷新,解决页面不会重新渲染的问题
},
randowPostions(tempArr,size){ //随机替换位置
var indexs = -1,
lengths = tempArr.length,
lastIndex = lengths - 1;
size = size === undefined? lengths:size;
while (++indexs < size) {
var rand = indexs + Math.floor(Math.random() * (lastIndex - indexs + 1));
value = tempArr[rand];
tempArr[rand] = tempArr[indexs];
tempArr[indexs] = value;
}
tempArr.length = size;
return tempArr;
},
randomArr(){
return Array.apply(null, {length: 81}).map(function (_, index) {
console.log(index)
return {
id: index,
number: (index % 9) + 1
};
})
}
},
created: function () {
this.cells = this.randomArr();
},
});
</script>
</body>
</html>
欢迎关注公众号(web学习吧),一起学习进步