-
v-on:click="onClidkCell(0, $event)
有v-on:click
的绑定事件,有$event
的接受数据。v-bind:n="n
传参 -
props: ["n"]
, //获取外面的属性n -
this.$emit("click", this.text);
//告诉外面我被点了,并且传递了text参数
<template>
<div class="wrapper">
<div>第{{n}}手</div>
<div class="chess">
<div class="row">
<!-- $event是接受cell发过来的参数this.text -->
<Cell v-on:click="onClidkCell(0, $event)" v-bind:n="n" />
<Cell v-on:click="onClidkCell(1, $event)" v-bind:n="n" />
<Cell v-on:click="onClidkCell(2, $event)" v-bind:n="n" />
</div>
<div class="row">
<Cell v-on:click="onClidkCell(3, $event)" v-bind:n="n" />
<Cell v-on:click="onClidkCell(4, $event)" v-bind:n="n" />
<Cell v-on:click="onClidkCell(5, $event)" v-bind:n="n" />
</div>
<div class="row">
<Cell v-on:click="onClidkCell(6, $event)" v-bind:n="n" />
<Cell v-on:click="onClidkCell(7, $event)" v-bind:n="n" />
<Cell v-on:click="onClidkCell(8, $event)" v-bind:n="n" />
</div>
</div>
<!-- <div>{{map}}</div> -->
<div>结果:{{result == null? '胜负未分' : `胜方为${result}` }}</div>
</div>
</template>
<script>
import Cell from "./Cell";
export default {
components: { Cell },
data() {
return {
n: 0,
result: null,
map: [
[null, null, null], //1. 声明一个二维数组
[null, null, null], //2.在用户点击的时候获取用户点击的序号和内容,把对应的i的text填到数组里面
[null, null, null] //3.调用tell判断谁胜谁负
]
};
},
methods: {
onClidkCell(i, text) {
console.log(`${i}被点击了,内容是:${text}`); //知道那个元素别点了,而且被点的内容也知道了,用一个数组map存下来
this.map[Math.floor(i / 3)][i % 3] = text;
this.n = this.n + 1;
this.tell();
},
tell() {
const map = this.map;
for (let i = 0; i < 2; i++) {
if (
map[i][0] !== null &&
map[i][0] == map[i][1] &&
map[i][1] == map[i][2]
) {
this.result = map[i][0];
}
}
for (let j = 0; j < 2; j++) {
if (
map[0][j] !== null &&
map[0][j] == map[1][j] &&
map[1][j] == map[2][j]
) {
this.result = map[0][j];
}
}
if (
map[0][0] !== null &&
map[0][0] == map[1][1] &&
map[1][1] == map[2][2]
) {
this.result = map[0][0];
}
if (
map[0][2] !== null &&
map[0][2] == map[1][1] &&
map[1][1] == map[2][0]
) {
this.result = map[0][2];
}
}
}
};
</script>
<style>
.row {
display: flex;
}
.wrapper {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
</style>
<template>
<div>
<!-- {{n}} 第几次被点-->
<div id="cell" v-on:click="onClickSelf">
<template v-if="a">{{text}}</template>
<template v-else></template>
</div>
</div>
</template>
<script>
export default {
props: ["n"], //获取外面的属性n
data() {
return { a: false, text: "" };
},
methods: {
//函数写在methods里面
onClickSelf() {
if(this.text !== "") {
return
}
this.a = true;
this.text = this.n % 2 == 0? "x" : "o"
this.$emit("click", this.text); //告诉外面我被点了,并且传递了text参数
}
}
};
</script>
<style>
#cell {
color: #9a55a3;
border: 1px solid black;
height: 100px;
width: 100px;
font-size: 50px;
display: flex;
justify-content: center;
align-items: center;
}
</style>
image.png
-
APP可以向cell传递信息,但是cell不能和cell传递。cell只能向APP传递事件
image.png
网友评论