You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue 3中如何根据父组件宽度向子组件传递Prop值

实现方案

因为父组件宽度用0.5vh这种相对单位定义,只有组件挂载后才能拿到真实DOM宽度,之前用computed会因为挂载前board ref未绑定DOM导致无法计算,这里提供两种可行解决办法:

1. 挂载后计算+监听尺寸变化(推荐)

这种方法既能在初始挂载时拿到正确尺寸,还能在窗口大小变化时自动更新方块尺寸,适配性更强:

修改父组件代码:

<template>
  <div ref="board" class="board">
    <square-component :square-size="squareSize" v-for="square in rows*cols" :key="square"></square-component>
  </div>
</template>

<script setup>
const board = ref(null)
const props = defineProps({
  cols: { type: Number, default: 10 },
  rows: { type: Number, default: 10 },
})

const squareSize = ref(0)

// 封装计算方块尺寸的函数
const calcSquareSize = () => {
  if (board.value) {
    // 和你说的board.offsetWidth/boardCols逻辑一致,用列数cols计算
    squareSize.value = board.value.offsetWidth / props.cols
  }
}

onMounted(() => {
  // 挂载后计算初始尺寸
  calcSquareSize()
  // 用ResizeObserver监听棋盘宽度变化,实时更新方块尺寸
  const observer = new ResizeObserver(calcSquareSize)
  board.value && observer.observe(board.value)
})
</script>

<style>
.board {
  width: .5vh;
  display: block; /* 确保棋盘是块级元素,能正确获取offsetWidth */
}
</style>

2. 监听ref绑定完成事件

如果不需要适配窗口变化,只需要初始渲染的尺寸,可以通过监听board ref的变化触发计算:

<script setup>
const board = ref(null)
const props = defineProps({
  cols: { type: Number, default: 10 },
  rows: { type: Number, default: 10 },
})

const squareSize = ref(0)

// 监听board ref的变化,当它绑定到真实DOM时计算尺寸
watch(board, (dom) => {
  if (dom) {
    squareSize.value = dom.offsetWidth / props.cols
  }
}, { immediate: true })
</script>

子组件小修正

你的子组件sizeStyle对象里的属性少了逗号,补上避免语法错误:

<script setup>
const props = defineProps({
  squareSize: { type: Number, required: true }
})

const sizeStyle = computed(() => {
  return {
    width: `${props.squareSize}px`,
    height: `${props.squareSize}px`
  }
})
</script>

另外,父组件的v-for要加上:key属性,避免Vue的渲染警告。

内容的提问来源于stack exchange,提问作者Miguel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 02:02:44