第 11 节:状态管理 V2 进阶——@Param / @Provider / @Monitor / @Computed
学习目标
- 用
@Param/@Event实现父→子传值、子→父发事件的单向数据流。 - 用
@Provider/@Consumer做跨层级共享。 - 用
@Computed写带缓存的派生值,用@Monitor一次监听多个深层路径。 - 掌握 V1→V2 的迁移对照,能读懂老工程并渐进迁移。
一、引入:父子怎么传、跨层怎么共享、派生值怎么自动算
上一节的 @Local + @ObservedV2/@Trace 解决了「组件内部状态怎么刷新」。但真实页面里:父组件要把数据传给子组件,子组件要通知父组件;隔三四层的主题色怎么共享;总价 = 单价×数量这种派生值怎么不用手动维护;任一字段变化怎么统一监听。这一节把 V2 剩下的四件套装配齐。
二、核心概念与正文
2.1 @Param / @Event / @Once:父子单向数据流
V2 里父子通信是显式的:@Param 是父→子输入(父变自动同步),@Event 是子→父回调,@Once 表示只吃父的首次值、之后父变不覆盖。V1 里 @Link 那种「子随手改父」的隐式通道没有了。
// ---- 子组件 ----
@ComponentV2
struct CounterCard {
@Param title: string = ''; // 父传,随父同步
@Param initValue: number = 0;
@Once snapshot: number = 0; // 只在首次拿父的值
@Event onAdd: (delta: number) => void = () => {
}; // 子向父发事件
@Local localCount: number = 0;
build() {
Column({
space: 8 }) {
Text(`${
this.title}:initValue=${
this.initValue}`)
Text(`snapshot=${
this.snapshot}(首次快照,之后不动)`)
Text(`子内部 localCount=${
this.localCount}`)
Button('子内部 +1').onClick(() => this.localCount++)
// 想改父的数据?调回调,不直接碰父
Button('通知父 +5').onClick(() => this.onAdd(5))
}
.padding(12)
}
}
// ---- 父组件 ----
@ComponentV2
struct CounterPage {
@Local parentCount: number = 0;
build() {
Column({
space: 12 }) {
Text(`父组件 parentCount = ${
this.parentCount}`)
Button('父自己 +1').onClick(() => this.parentCount++)
CounterCard({
title: '计数器卡片',
initValue: this.parentCount, // @Param:随父同步
snapshot: this.parentCount, // @Once:只吃首次值
onAdd: (d: number) => {
this.parentCount += d; } // 父显式决定怎么改
})
}
.padding(20)
}
}
对照 V1 记:@Param 像 @Prop(单向同步);@Once 像「只吃一次的 @Prop」;@Event 就是把 @Link 的「改父」方向拆成显式回调。数据流永远是父→子的状态 + 子→父的事件,谁改的、在哪改的,在传参处一眼可见。@Once 的典型场景是编辑弹窗:打开时把原始值带进来,之后用户怎么改都不被父组件刷新覆盖。
2.2 @Provider / @Consumer:跨层级共享
V2 版跨层共享是 @Provider / @Consumer(注意拼写:V2 是 Consumer 带 r,V1 是 Consume)。语义比 V1 干净:Consumer 默认只读跟随,要改值得走 @Event 或在 Provider 侧提供修改方法。
@ObservedV2
class Theme {
@Trace color: ResourceColor = Color.Blue;
}
@ComponentV2
struct BottomConsumer {
// 隔多少层都能取到,按变量名匹配
@Consumer theme: Theme = new Theme();
build() {
Text('深层文字').fontColor(this.theme.color)
}
}
@ComponentV2
struct ProviderPage {
@Provider theme: Theme = new Theme();
build() {
Column({
space: 10 }) {
Button('改主题为红').onClick(() => this.theme.color = Color.Red)
BottomConsumer()
}
.padding(20)
}
}
它支持别名(@Provider('key')),也支持直接链接 AppStorage 键(@Provider('storageKey'))。和 V1 @Provide/@Consume 最大差别:Consumer 端默认不能「随手改」,写入口收敛在 Provider 侧。
2.3 @Computed:带缓存的派生值
@Computed 是派生属性:它依赖的 @Trace 字段一变,自动重算并重绘,带缓存。用 get 访问器写法:
@ObservedV2
class Cart {
@Trace price: number = 0;
@Trace count: number = 0;
}
@ComponentV2
struct ShopPage {
@Local cart: Cart = new Cart();
// 派生:总价 = 单价 × 数量。依赖的字段变了自动重算
@Computed
get total(): number {
return this.cart.price * this.cart.count;
}
build() {
Column({
space: 8 }) {
Text(`单价 ${
this.cart.price} × 数量 ${
this.cart.count}`)
// total 是 @Computed,不用自己手动更新
Text(`总价 = ${
this.total}`).fontSize(24).fontColor(Color.Red)
Button('单价 +1').onClick(() => this.cart.price++)
Button('数量 +1').onClick(() => this.cart.count++)
}
.padding(20)
}
}
规则:必须是 getter;自动追踪 getter 里读到的 @Trace/@Local 字段;依赖不变时多次读取只算一次(有缓存);getter 里不要产生副作用(改状态、发请求),它可能在任意时机被求值。它替代了 V1 里「@Watch 里手动维护派生状态」的写法。
2.4 @Monitor:一次监听多个深层路径
@Monitor 是 V2 的监听利器:一次可监听多个状态、多个 @Trace 路径,深层变化也能收到回调,回调参数是 IMonitor:
@ComponentV2
struct ShopPage {
@Local cart: Cart = new Cart();
@Local log: string = '';
@Computed
get total(): number {
return this.cart.price * this.cart.count;
}
// 同时监听 price 和 count 两个路径
@Monitor('cart.price', 'cart.count')
onCartChange(monitor: IMonitor) {
this.log = `监听触发:price=${
this.cart.price}, count=${
this.cart.count}`;
}
build() {
Column({
space: 8 }) {
Text(`总价 = ${
this.total}`).fontColor(Color.Red)
Text(this.log).fontSize(12).fontColor(Color.Gray)
Button('单价 +1').onClick(() => this.cart.price++)
Button('数量 +1').onClick(() => this.cart.count++)
}
.padding(20)
}
}
路径支持点分深层写法('user.profile.city'),前提是中间每一层都是 @ObservedV2 类、目标字段是 @Trace。一次监听多路径用逗号隔开,任一变化都触发。典型用途:表单页「任一字段变化就自动保存草稿」——V1 要给每个字段各写一个 @Watch,V2 一个 @Monitor 全收。
三、完整示例:V2 全家桶购物车
把 @ObservedV2/@Trace、@Local、@Computed、@Monitor 串成一个完整场景:
@ObservedV2
class CartItem {
@Trace name: string;
@Trace price: number;
@Trace count: number;
constructor(name: string, price: number, count: number) {
this.name = name; this.price = price; this.count = count;
}
}
@ComponentV2
struct CartPage {
@Local items: CartItem[] = [
new CartItem('无线耳机', 299, 1),
new CartItem('手机壳', 39, 2)
];
// 派生:总价 = 所有行 price*count 之和
@Computed
get total(): number {
let sum = 0;
for (const it of this.items) {
sum += it.price * it.count;
}
return sum;
}
// 任一行数量变化都记日志(深层路径也能监到)
@Monitor('items')
onItemsChange(m: IMonitor) {
console.info(`购物车变化,当前总价 ${
this.total}`);
}
build() {
Column({
space: 10 }) {
ForEach(this.items, (it: CartItem) => {
Row() {
Text(`${
it.name} ¥${
it.price} × ${
it.count}`).layoutWeight(1)
Button('+').width(40).onClick(() => it.count++)
}
})
Divider()
Text(`合计:¥${
this.total}`).fontSize(22).fontColor(Color.Red)
}
.padding(20)
}
}
整个过程没有 @ObjectLink、没有手动联动:行数据是 @ObservedV2 类,总价 @Computed 自动算,数量变化 @Monitor 自动打日志,状态流向一目了然。
四、踩坑提示
⚠️ 坑 1:@Monitor 回调永远不进。 路径字符串要和实际 @Trace 字段完全对应,写错路径不报错、只是不触发。写完先手动点一遍按钮验证回调进没进。
⚠️ 坑 2:@Computed getter 里改状态。 会产生副作用甚至死循环。getter 必须是纯计算,只依赖、不改写。
⚠️ 坑 3:@Event 没传实现就调用。 子组件调用 @Event 时父组件必须传了实现,否则报空。默认给
= () => {}兜底更安全。⚠️ 坑 4:V1/V2 装饰器混在一个组件。 编译直接报错。整组件要么 V1 要么 V2;迁移期允许「V2 页面嵌个别 V1 老组件」,但别长期混搭。
V1→V2 迁移对照速查:
| 职责 | V1 | V2 |
|---|---|---|
| 组件装饰器 | @Component | @ComponentV2 |
| 组件内状态 | @State | @Local |
| 父→子单向 | @Prop | @Param / @Once |
| 父子双向 | @Link | @Param + @Event |
| 跨层共享 | @Provide/@Consume | @Provider/@Consumer |
| 可观测类 | @Observed + @ObjectLink | @ObservedV2 + @Trace |
| 变化监听 | @Watch | @Monitor |
| 派生计算 | @Watch 手动联动 | @Computed |
五、小结
- V2 数据流是单向的:@Param 父→子入参,@Event 子→父回调,不再有 @Link 那种随手改父。
- @Provider/@Consumer 跨层共享,Consumer 默认只读,写入口收敛在 Provider 侧。
- @Computed 写带缓存的派生值(getter,纯计算);@Monitor 一次监听多个 @Trace 深层路径。
- 新工程从第一天就用 V2:@ComponentV2 + @Local + @ObservedV2/@Trace + @Param/@Event,写模型类时顺手加 @Trace。
六、思考题 / 实践任务
- 动手任务:在购物车示例上加一个「数量上限 5」,在 @Monitor 里拦截超过上限的变化并回退。
- 动手任务:用 @Provider/@Consumer 做一个深色/浅色主题切换,根组件 @Provider 持有 Theme,深层组件 @Consumer 读取颜色。
- 实践任务:把第 9 节某个 V1 计数器按迁移表改成 V2 写法,对比样板代码量。
- 思考题:为什么 V2 要取消双向绑定、改成 @Event 显式回调?在三层以上嵌套的页面里,这能帮你避免什么?
到这里,你已经能用 ArkTS + ArkUI + 状态管理 V2 写出一个数据会动、组件能复用、跨层能共享的完整页面。接下来的小册内容会进入 Navigation 多页面导航、网络与数据持久化、系统能力调用,最后是三个完整实战项目——把这套地基真正用到能上线的应用里。