@Observed装饰数据model
@Observed
export class CartModel {
id?:number
goods_name?:string
goods_code?:string
goods_big_logo?:string
goods_price?:number
goods_count?:number
goods_checked?:number
}
父页面使用反例,使用字面量赋值的方式,子组件修改数据,数据改变,页面不会变化
import { ProductItem } from '../view/ProductItem'
@Component
export struct Cart {
@State carts: CartModel[] = [
{
"id": 4,
"goods_name": "创维(Skyworth)65M6E 65英寸 4K超高清智能酷开网络液晶电视",
"goods_big_logo": "https://inews.gtimg.com/news_bt/O7ZsQ9IrSfcWAWLPeaRcfeEt5FdyeTfnFYrSGmDSKlU0sAA/1000",
"goods_code": "57443",
"goods_price": 4999,
"goods_count": 1,
"goods_checked": 0
},
]
build() {
List({ space: 10 }) {
ForEach(this.carts, (item: CartModel, index: number) => {
ListItem() {
ProductItem({ item: item,computedTotalPrice:this.computedTotalPrice })
}
}, (item: CartModel) => JSON.stringify(item.id))
}
.padding({ bottom: 10 })
}
}
父页面使用正例 ,使用new class类的方式
import { ProductItem } from '../view/ProductItem'
@Component
export struct Cart {
@State carts: CartModel[] = []
aboutToAppear(): void {
const cart01 = new CartModel()
cart01.id = 1
cart01.goods_name = "创维(Skyworth)65M6E 65英寸 4K超高清智能酷开网络液晶电视"
cart01.goods_code = "57443"
cart01.goods_big_logo= "https://inews.gtimg.com/news_bt/O7ZsQ9IrSfcWAWLPeaRcfeEt5FdyeTfnFYrSGmDSKlU0sAA/1000"
cart01.goods_price = 4999
cart01.goods_count = 1
cart01.goods_checked = 0
this.carts.push(cart01)
const cart02 = new CartModel()
cart02.id = 2
cart02.goods_name = "创维(Skyworth)65M6E 65英寸 4K超高清智能酷开网络液晶电视"
cart02.goods_code = "57443"
cart02.goods_big_logo= "https://inews.gtimg.com/news_bt/O7ZsQ9IrSfcWAWLPeaRcfeEt5FdyeTfnFYrSGmDSKlU0sAA/1000"
cart02.goods_price = 1999
cart02.goods_count = 1
cart02.goods_checked = 0
this.carts.push(cart02)
}
build() {
List({ space: 10 }) {
ForEach(this.carts, (item: CartModel, index: number) => {
ListItem() {
ProductItem({ item: item,computedTotalPrice:this.computedTotalPrice })
}
}, (item: CartModel) => JSON.stringify(item.id))
}
}
}
子组件使用
import { CartModel } from '../viewmodel/CartModel'
@Component
export struct ProductItem {
@ObjectLink item: CartModel
}
参考文档:@Observed装饰器和@ObjectLink装饰器:嵌套类对象属性变化