我正在开发一个 Vue-Tac-Toe 应用程序,只有 4 个乐趣,但现在有点卡住了。
<小时/>问题:如何将cellRow
的prop传递给组件Field.vue
?
我想要的:每个字段都应该有一个唯一的标识,例如左上角的图 block (第一个)应该被识别为cellRow: 0 & cellId: 0
因为我需要有信息来简单检查井字游戏获胜(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>
最佳答案
如果我正确理解了问题,您可以将 Row
组件的 cellRow
属性进一步简单地传递为 Field
组件的属性。
Row(将 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>
关于javascript - 如何在 Vue.js 中将 prop 传递给父组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54275285/