如何在模板渲染时获取Vue组件父元素样式以计算卡牌边距
卡牌游戏手牌布局问题
我正在开发一款卡牌游戏,需要获取玩家手牌容器(父元素)的宽度来计算卡牌的边距。试过几种方法都没成功:
- 通过
this.$el从模板元素获取样式,但渲染时元素尚未创建 - 通过
$refs获取组件父元素,同样元素未创建 - 尝试创建带指定ID的元素提取样式后删除,也失败了
预期卡牌在手牌中呈现重叠错落的布局(类似常见的玩家手牌排列,卡牌依次向右叠加,整体居中)。相关代码如下:
App.vue
<template> <div id="hand" ref="hand"> <Hand :hand="hand" :card_width="150"/> </div> </template> <script> import Hand from "./components/Hand.vue"; export default { data () { return { message: 'ONE GAME!', colors: ["#C90000", "#379711", "#0956BF", "#FFC700"], cards: [0,1,2,3,4,5,6,7,8,9,'reverse', 'skip', 'draw2', 'wild', 'wild4'], top_card: {card: 1, color: 1}, hand: [] } }, components: { 'Hand': Hand }, created: function() { this.hand = [ {card:1, color: this.colors[1]}, {card:1, color: this.colors[2]}, {card:1, color: this.colors[3]}, ] } } </script>
Hand.vue
<script> import Card from "./Card.vue"; export default { data() { return {} }, props: { hand: Array, card_width: Number, }, components: { Card, }, methods: { calculateMarginLeft(index, cards_count) { return parseInt(getComputedStyle(this.$refs.hand).width) - this.card_width / (cards_count - 1) * index + 'px'; }, }, }; </script> <template> <div class="hand" ref="hand"> <Card :style="{'position':'absolute', 'z-index':index, 'margin-left': calculateMarginLeft()}" v-for="(card, index) in hand" :card="card.card" :color="card.color" :key="index" :width="this.card_width" /> </div> </template> <style> #hand { width: 80%; } </style>
Card.vue
<template> <div v-html="this.cardsSvg[this.card]" class="card"></div> </template> <script> export default { props: ['card','color', 'width'], data () { return { 'cardsSvg': [some svg images for cards] } }, } </script> <style> .card { fill: v-bind(color); width: v-bind(width) + 'px'; height: 1.495 * v-bind(width) + 'px'; } </style>
内容的提问来源于stack exchange,提问作者Atty
相关产品推荐
相关产品推荐

