- 对react示例拙略的模仿👉 教程
<template>
<div class="body">
<el-divider></el-divider>
<h2 @click="reset" class="h2">{{ text }}: {{ isFork ? "❌" : "⭕" }}</h2>
<div class="board">
<div class="board-row" v-for="row of 3">
<button v-for="index of 3" class="square" @click="handleChess(row+index*10,$event)"/>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
isFork: true,
forkList: [],
circleList: [],
text: "下一步该",
status: false,
}
},
methods: {
handleChess(index, event) {
if (this.status || event.target.innerText!=="") return
event.target.innerText = this.isFork ? "❌" : "⭕";
this.isFork ? this.forkList.push(index) : this.circleList.push(index)
if (this.calculateWinner()) {
this.text = '🎉🎉🎉获胜者是'
this.status = true
} else {
this.isFork = !this.isFork;
}
},
// 11 21 31
// 12 22 32
// 13 23 33
calculateWinner() {
const lines = [
[11, 21, 31],
[12, 22, 32],
[13, 23, 33],
[11, 12, 13],
[21, 22, 23],
[31, 32, 33],
[11, 22, 33],
[13, 22, 31],
];
let flag = false
let forkList = this.forkList;
let circleList = this.circleList;
for (const e of lines) {
const [a, b, c] = e
if (forkList.includes(a) && forkList.includes(b) && forkList.includes(c)) {
flag = true
}
if (circleList.includes(a) && circleList.includes(b) && circleList.includes(c)) {
flag = true
}
if (flag) break
}
return flag
},
reset(){
const reset = {
isFork: true,
forkList: [],
circleList: [],
text: "下一步该",
status: false,
}
// 浅拷贝
Object.assign(this.$data,reset)
let squares = window.document.getElementsByClassName("square");
Array.prototype.forEach.call(squares,e=>e.innerText = "")
}
}
}
</script>
<style scoped>
* {
box-sizing: border-box;
}
h2 {
margin-bottom: 20px;
}
code {
font-size: 1.2em;
}
.body {
font-family: sans-serif;
margin: 20px 140px;
padding: 0;
}
.square {
background: #fff;
border: 1px solid #999;
float: left;
font-size: 24px;
font-weight: bold;
line-height: 34px;
height: 34px;
margin-right: -1px;
margin-top: -1px;
padding: 0;
text-align: center;
width: 34px;
}
.board-row:after {
clear: both;
content: '';
display: table;
}
.status {
margin-bottom: 10px;
}
.game {
display: flex;
flex-direction: row;
}
.game-info {
margin-left: 20px;
}
</style>