【高心星出品】
文章目錄
- V2裝飾器@once的使用
- 概念
- 一、核心作用與規則
- 二、適用場景
- 案例
V2裝飾器@once的使用
概念
在鴻蒙ArkTS開發中,@Once
裝飾器用于實現子組件僅接受父組件傳遞的初始值,后續父組件數據變化不再同步至子組件。以下是其核心要點:
一、核心作用與規則
- 初始化同步一次
@Once
與@Param
結合使用,子組件僅在初始化時接收父組件傳遞的值,后續父組件數據更新時不會觸發同步。 - 強制依賴關系
@Once
必須與@Param
搭配使用,單獨使用或與其他裝飾器(如@Local
)結合會編譯失敗。- 裝飾順序不影響功能,
@Param @Once
或@Once @Param
均有效。
- 本地修改支持
結合@Once
后,子組件可以修改@Param
變量值并觸發UI刷新,此時行為類似@Local
,但仍保留初始值傳遞能力。
二、適用場景
- 固定初始值:父組件傳遞配置參數(如主題色、默認尺寸),子組件僅需初始化時使用。
- 獨立維護狀態:子組件基于父組件初始值構建自身狀態后,不再依賴外部更新。
案例
父組件(oncepage):
點擊按鈕時,@Local
修飾的count
自增,并通過child3({ count: this.count })
傳遞最新值給子組件。但子組件僅在首次渲染時接收初始值(如10
),后續父組件的count
變化不會更新子組件。
子組件(child3):
點擊按鈕時,子組件內部count
自增并更新UI,但父組件的count
始終保持獨立狀態(例如父組件count
為15時,子組件可能顯示為12)。
@ComponentV2
struct child3 {// 強制父組件傳參 并且只會初始化一次@Require @Once @Param count:numberbuild() {Column() {Button('child count: ' + this.count).width('60%').onClick(() => {//@once裝飾的變量 這里可以更新count值this.count+=1})}.width('100%').padding(20)}
}@Entry
@ComponentV2
struct oncepage {@Local count: number = 10;build() {Column({ space: 20 }) {Button('page count: ' + this.count).width('60%').onClick(() => {this.count += 1})// child count與 父組件count單向綁定child3({ count: this.count })}.height('100%').width('100%')}
}
父子組件同步的數據為數組的時候,使用@once和@param修改數組中元素不會造成單向同步而是會形成雙向同步效果,例如下面案例,父子組件數據會同時改變。
@ComponentV2
struct child4 {// 強制父組件傳參 并且只會初始化一次@Require @Once @Param arr:number[]build() {Column() {Button('child count: ' + this.arr[0]).width('60%').onClick(() => {//@once裝飾的變量 這里可以更新count值this.arr[0]+=1})}.width('100%').padding(20)}
}@Entry
@ComponentV2
struct oncepage1 {@Local arr: number[] = [1,2,3];build() {Column({ space: 20 }) {Button('page count: ' + this.arr[0]).width('60%').onClick(() => {this.arr[0] += 1})// child count與 父組件count單向綁定child4({ arr: this.arr })// 使用深度拷貝 就會造成隔離不會雙向同步// child4({arr:[...this.arr]})}.height('100%').width('100%')}
}
裝飾器組合 | 同步方式 | 內存關系 | 適用場景 |
---|---|---|---|
@Param | 雙向同步 | 共享引用 | 需要實時聯動的組件(如協同編輯器) |
@Once @Param | 單次初始化同步 | 共享引用* | 基于初始值的獨立運作組件 |
@Param + 深拷貝 | 完全隔離 | 獨立內存 | 需要數據隔離的安全場景 |