我正在开发Vue-Tac-Toe应用程序,仅4个乐趣,而我现在却遇到了困难。
问题:如何将cellRow
的属性传递给组件Field.vue
?
我想要的内容:每个字段都应具有唯一的标识,例如,左上方(第一个)的图块应将其识别为cellRow: 0 & cellId: 0
因为我需要掌握一些信息来简单地检查tic-tac-toe win(一行中有3个,等等)
GameField.vue:我们有基于行和单元格的布局。
<template>
<div id="game-field">
<div class="container">
<template v-for="(rows, index) in 3">
<Row :cell-row="index" />
</template>
</div>
</div>
</template>
<script>
import Row from './Row.vue';
export default {
components: {
Row,
},
data() {
return {};
},
};
</script>
<style lang="scss" scoped>
.container {
width: 400px;
margin: 10% auto 0;
}
</style>
Row.Vue:每行有3个字段。从0-2。
<template lang="html">
<div class="row">
<Field
v-for="(fieldId, index) in 3"
:key="fieldId"
:cell-id="index"
/>
</div>
</template>
<script>
import Field from './Field.vue';
export default {
components: {
Field,
},
props: {
cellRow: {
type: Number,
default: 0,
},
},
data() {
return {
};
},
};
</script>
<style lang="scss" scoped>
</style>
Field.vue:
<template lang="html">
<div class="cell">
<slot />
</div>
</template>
<script>
export default {
props: {
cellId: {
type: Number,
default: 0,
},
},
data() {
return {};
},
};
</script>
<style lang="scss" scoped>
.cell {
margin: 1px 3px -3px -1px;
width: 100px;
height: 100px;
background-color: white;
display: inline-block;
cursor: pointer;
}
</style>
答案 0 :(得分:1)
如果我对问题的理解正确,则可以进一步将cellRow
组件的Row
属性作为Field
组件的属性。
行(将cellRow
作为道具传递给Field
)
<template lang="html">
<div class="row">
<Field
v-for="(fieldId, index) in 3"
:key="fieldId"
:cell-id="index"
:row-id="cellRow" // passing row index to Field component
/>
</div>
</template>
...
字段
...
<script>
export default {
props: {
cellId: {
type: Number,
default: 0,
},
rowId: { // defining new prop type
type: Number,
default: 0,
},
},
...
};
</script>
这是一个小演示:
Vue.config.devtools = false;
Vue.config.productionTip = false;
Vue.component('Row', {
template:
`
<div class="row">
<Field
v-for="(fieldId, index) in 3"
:key="fieldId"
:cell-id="index"
:row-id="cellRow"
/>
</div>
`,
props: {
cellRow: {
type: Number,
default: 0
}
}
})
Vue.component('Field', {
template:
`
<div class="cell">
<p>Row Id: {{ rowId }}</p>
<p>Cell Id: {{ cellId }}</p>
</div>
`,
props: {
cellId: {
type: Number,
default: 0
},
rowId: {
type: Number,
default: 0
}
}
})
new Vue({
el: '#demo',
template:
`
<div id="game-field">
<div class="container">
<template v-for="(rows, index) in 3">
<Row :cell-row="index" />
</template>
</div>
</div>
`
})
.cell {
margin: 1px 3px 3px 1px;
width: 100px;
height: 100px;
background-color: gray;
display: inline-block;
cursor: pointer;
color: white;
padding: 5px;
}
.container {
width: 400px;
margin: 10% auto 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo"></div>