1模板
<template>
<div>
<ul ref="refUl" class="dom" :class="isWho" @click="cellClick">
<li class="cell" data-click="click"></li>
<li class="cell" data-click="click"></li>
<li class="cell" data-click="click"></li>
<li class="cell" data-click="click"></li>
<li class="cell" data-click="click"></li>
<li class="cell" data-click="click"></li>
<li class="cell" data-click="click"></li>
<li class="cell" data-click="click"></li>
<li class="cell" data-click="click"></li>
</ul>
<div id="win" :class="isWin ? 'block' : ''">
<div>
<p v-if="isDraw">平局</p>
<p v-else>{{whoWin}} 赢了</p>
<button @click="reSet">重新开始</button>
</div>
</div>
</div>
</template>
2,js部分
<script lang="ts">
import { onMounted, reactive, ref, toRefs } from 'vue';
enum XO{ X = "x", O = "o"}
export default {
name: 'HelloWorld',
setup(){
const refUl = ref();
const step = ref(0);
//哪些情况会赢
const winArr = [
[0,1,2],[3,4,5],[6,7,8],
[0,3,6],[1,4,7],[2,5,8],
[0,4,8],[2,4,6]
];
// 检查是否有人赢了
function checkWin(who: XO): boolean{
const refLi = refUl.value.children;
return winArr.some((el) => {
const arr1 = el[0];//el为[0,1,2]时 el[0]就为0 依次类推
const arr2 = el[1];
const arr3 = el[2];
//循环判断 winArr里面的三个元素是否同时含有同一个class
if(
refLi[arr1].classList.contains(who) &&
refLi[arr2].classList.contains(who) &&
refLi[arr3].classList.contains(who)
){
return true;
}
return false;
})
}
const data = reactive({
isWho: ref(XO.X),//现在谁下棋
isWin: ref(false),//是不是赢了
whoWin: ref(),//谁赢了
isDraw: ref(false),//是否平局
cellClick: function(e: any): void {
if(e.target.dataset.click == 'click'){
e.target.className = data.isWho
e.target.dataset.click = 'none'
data.isWin = checkWin(data.isWho);
data.whoWin = data.isWho;
data.isWho = data.isWho == XO.X ? XO.O : XO.X;
step.value++;
//如果下了9步还没有谁赢 就是平局
if(!data.isWin && step.value == 9){
data.isWin = true;
data.isDraw = true;
}
}
},
reSet: function(): void {
const refLi = refUl.value.childNodes;
data.isWin = false;
data.isDraw = false;
data.isWho = XO.X;
step.value = 0;
refLi.forEach((element: any) => {
element.className = "cell"
element.dataset.click = 'click'
});
}
})
const refData = toRefs(data);
return {
...refData,
refUl
}
}
};
</script>
3,css部分
<style scoped lang="less">
.x{
.cell{
&::before{
content: "X";
}
&:hover{
color:#ccc;
}
}
}
.o{
.cell{
&::before{
content: "O";
}
&:hover{
color:#ccc;
}
}
}
.dom{
width: 300px;
display: flex;
flex-wrap: wrap;
font-size: 40px;
li{
width: 100px;
height: 100px;
border: 1px solid #ccc;
text-align: center;
line-height: 100px;
cursor: pointer;
color: #eee;
}
.x{
&::before{
content: "X";
}
color: green;
}
.o{
&::before{
content: "O";
}
color: green;
}
}
#win{
position: absolute;
top:0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, .5);
display: none;
>div{
width: 200px;
height: 150px;
text-align: center;
padding-top: 50px;
background-color: #fff;
position: absolute;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -70px;
}
p{
font-size: 18px;
}
}
.block{display:block!important;}
</style>