[英]Why isn't Vue prop resetting after re-rendering component?
我正在嘗試創建一個可以通過單擊按鈕更改大小的板。 該板具有寬度和高度屬性,這些屬性確定它的寬度和高度有多少單元格。 當我更改這些寬度和高度屬性時,板子會重新渲染為正確的大小,但它的道具(即一個 coords 道具,它是板上單元格的 position 的 [x,y] 數組)沒有正確更新.
當頁面第一次呈現時(板的寬度和高度為 10)並且我 console.log 板的單元格,左上角的單元格的坐標為 [0,0],這是正確的。 截屏。
但是,在將寬度和高度分別重置為 5 后,左上角的單元格的坐標為 [4,0],我不明白為什么。 截屏。
這是我的 App.vue 代碼:
<template> <button @click="resetBoard()">reset game with new board dimensions</button> <div:style="{ width: boardWidth, height: boardHeight }"> <div v-for="y in height":key="y"> <BoardCell v-for="x in width" ref="cells":coords="[x - 1, y - 1]":key="y * width + x" /> </div> </div> <button @click="logCells">log cells to console</button> </template> <script> import BoardCell from "./components/BoardCell.vue"; export default { name: "App", components: { BoardCell }, data() { return { width: 10, height: 10, }; }, computed: { boardWidth() { return (this.width * 40).toString() + "px"; }, boardHeight() { return (this.height * 40).toString() + "px"; }, }, methods: { resetBoard() { this.width = 5; this.height = 5; }, logCells(){ console.log('this.$refs.cells:') console.log(this.$refs.cells) } }, }; </script>
這是我的單元組件代碼:
<template> <div class="cell"> </div> </template> <script> export default { props: ['coords'] } </script> <style scoped>.cell { width: 40px; height: 40px; float: left; line-height: 0px; background-color: limegreen; border: 1px green solid; box-sizing: border-box; } </style>
我認為這個問題可能與關鍵:key="y * width + x"
有關。 它可能不是唯一的。
當您更改板子的大小時,Vue 渲染器會嘗試重用前一個板子中的元素,並且由於前一個板子具有相同鍵的元素,您可能會在新板子中看到舊元素。
例如:
:key="11"
:key="11"
,因此 Vue 渲染器將在此處重用舊元素。為避免這種情況,我認為您應該嘗試為不同的板創建唯一的密鑰
一個例子
<div v-for="y in height" :key="`${height}x${width}[${y}]`">
<BoardCell
v-for="x in width"
ref="cells"
:coords="[x - 1, y - 1]"
:key="`${height}x${width}[${y}][${x}]`"
/>
</div>
在該示例中,您將擁有10x10[1][1]
或5x5[2][1]
類的鍵。
實際上,您在控制台記錄的 ref 不是左上角的單元格,而是右上角。 v-for 中使用的 $refs 數組的順序不能保證與源數組匹配。 根據文檔:
$refs 僅在組件被渲染后才被填充,並且它們不是響應式的。 它僅作為直接子操作的逃生艙口 - 您應該避免從模板或計算屬性中訪問 $refs。
我將您的代碼放入沙箱並使用Vue DevTools我使用組件檢查器驗證了左上角單元格的坐標是否正確,您可以在此處看到(我更改了顏色以使單元格突出顯示更容易看到)
如果您確實需要跟蹤單元格及其正確順序,您可以制作一組“單元格”對象。 看起來您可以從中受益,每個 object 都可以存儲它自己的坐標。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.