我注意到在 Vue 中您可以更改作為 Props 傳遞的物件欄位,并且它會更改父級中的這些欄位。
這是一個糟糕的技術嗎?應該避免,還是可以使用?這種方法有什么注意事項?
例子:
父.vue:
<script setup>
import { reactive } from 'vue';
import ChildInput from "./Child.vue";
</script>
<script>
const myObj = reactive({'val':'Default text'});
</script>
<template>
<ChildInput :passedObj="myObj" />
<div>
It's a parent input:
<input v-model="myObj.val">
</div>
</template>
孩子.vue:
<script setup>
const props = defineProps({
passedObj: {
type: Object,
required: true,
},
})
const dropValue = function() {
props.passedObj.val = "Changed text";
}
</script>
<template>
<div>
<label>
It's a child input:
<input v-model="passedObj.val">
<button @click="dropValue">Change text</button>
</label>
</div>
</template>
您可以在此處查看此示例。
uj5u.com熱心網友回復:
禁止淺 prop 突變,因為 props 物件是只讀的。
深度道具突變是一種不好的做法,應該避免。一個原因是這使資料流更加復雜且難以跟蹤,在這種情況下無意識地發生了這種情況,這解釋了為什么這是一個問題。另一個可能的原因是性能可能會受到影響,因為這種情況不在常用范圍內,盡管我目前還不知道此類優化問題。
官方推薦在 props 需要突變時使用v-model雙向系結,這樣突變發生在父組件中,需要除錯時可以通過 Vue 事件進行跟蹤。當一個 prop 發生深度變異時,它會被克隆到一個子行程中并發送給一個父行程。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/468383.html
上一篇:如何將物件陣列減少到所需的格式?
下一篇:如何添加新的患者mysql?
