我正在制作一个有n x n个正方形组件的电路板组件.我想根据棋盘的宽度来设定正方形的大小,大概是board.offsetWidth / boardCols.

我如何才能将正方形的大小或父母的宽度传递给子元素?

父级宽度设置为0.5vh,因此在组件安装之前,我不能知道电路板的宽度(以像素为单位),但props 在安装之前通过.

以下是父组件:

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

<script setup>
//I'm working on Nuxt, no imports needed
const board = ref()
const props = defineProps({
  cols: {type: Number, default: 10},
  rows: {type: Number, default: 10},
})

const squareSize = computed(() => {
  //here, board value is undefined
  const squareSize = board.value.offsetWidth / props.rows
  return squareSize
})
</script>

<style>
.board {
  width: .5vh
}
</style>

这是子元素:

<template>
  <div :style=[sizeStyle, myOtherComputedStyles]></div>
</template>

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

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

有没有办法实现这一点?

推荐答案

Vue SFC Playground

你的squareSize没有react .

  1. 你应该使用board.value?.offsetWidth,所以在安装上它只会得到0
  2. 您应该向它添加一些react 值作为依赖项(不需要在计算中使用它).在本例中,我使用了width: 50vw,因此我们需要一些react 性引用,具体取决于窗口的宽度.我更改了窗口resize事件的引用:
<script setup>

//I'm working on Nuxt, no imports needed
const board = ref()
const props = defineProps({
  cols: {type: Number, default: 10},
  rows: {type: Number, default: 10},
});

const windowWidth = ref(document.body.clientWidth);
window.addEventListener('resize', () => windowWidth.value = document.body.clientWidth);

const squareSize = computed(() => (windowWidth.value, (board.value?.offsetWidth ?? 0)/ props.rows ));
</script>

Javascript相关问答推荐

一次仅播放一个音频

if/else JavaScript中的条件行为

jQuery提交按钮重新加载页面,即使在WordPress中使用preventDefault()

如何使覆盖div与可水平滚动的父div相关?

切换时排序对象数组,切换不起作用

不能将空字符串传递给cy.containes()

环境值在.js文件/Next.js中不起作用

JavaScript不重定向配置的PATH

在画布中调整边上反弹框的大小失败

为什么当我更新数据库时,我的所有组件都重新呈现?

每次重新呈现时调用useState initialValue函数

将基元传递给THEN处理程序

如何用javascript更改元素的宽度和高度?

FireBase FiRestore安全规则-嵌套对象的MapDiff

将Singleton实例设置为未定义后的Angular 变量引用持久性行为

在此div中添加一个类,并在一段时间后在Java脚本中将其删除

找不到处于状态的联系人

错误400:当我试图在React中使用put方法时,该字段是必需的

如何动态呈现适合未知屏幕大小的最大数量的表行?苗条的

正在发出错误的URL请求