Background Knowledge
Create a model and choose a random one, and navigate to another page.
Implementation Steps
1) Create a model
2) Create a button named perfume of the day. When we click on it, it shows a random item from the Perfume Model.
3) Select the random item from all the items, and transfer this item to the next page
4) Show this random item on this page
Code Snippet / Configuration
1) Create a model
export interface Perfume {
name: string;
image: Resource;
category: string;
description: string;
}
export const dummyPerfume: Perfume[] = [
{
name: 'Perfume1',
image: $r('app.media.dummyperfume1'),
category: 'Romantic',
description: 'desc1'
},
{
name: Perfume2',
image: $r('app.media.dummyperfume2'),
category: 'Masculine',
description: 'desc2'
},
{
name: 'Perfume3',
image: $r('app.media.dummyperfume3'),
category: 'Unisex',
description: 'desc3'
},
{
name: 'Perfume4',
image: $r('app.media.dummyperfume4'),
category: 'Night',
description: 'desc4'
},
{
name: 'Perfume5',
image: $r('app.media.dummyperfume5'),
category: 'Seasonal',
description: 'desc5'
},
]
2) HomePage.ets
@State selectedPerfume: Perfume | null = null;
3) Create a button named perfume of the day. When we click on it, it shows a random item from the Perfume Model
Button('Perfume of the Day')
.height(50)
.margin(2)
.width('100%')
.backgroundColor('#ffd4c890')
.onClick(() => {
const randomIndex = Math.floor(Math.random() * dummyPerfume.length);
this.selectedPerfume = dummyPerfume[randomIndex];
router.pushUrl({
url: 'pages/PerfumeOfTheDayPage',
params: {
name: this.selectedPerfume.name,
image: this.selectedPerfume.image,
category: this.selectedPerfume.category,
description: this.selectedPerfume.description,
}
})
})
4) Show the random perfume on the page.
PerfumeOfTheDayPage.ets
import { Perfume } from '../model/PerfumeModel';
import { router } from '@kit.ArkUI';
@Entry
@Component
struct PerfumeOfTheDayPage {
params: Perfume = router.getParams() as Perfume;
build() {
Column() {
Text('💕 Perfume of Today 💕').fontSize(12)
.padding({ bottom: 10 })
Image(this.params.image)
.height(100)
.width(120)
.borderRadius(10)
.objectFit(ImageFit.Contain)
.padding({ bottom: 5 })
Text(this.params.name).fontSize(11).fontWeight(FontWeight.Bold).fontColor(Color.Black).padding({ bottom: 2 })
Text(this.params.category).fontSize(9).fontColor(Color.Black)
}
.justifyContent(FlexAlign.Center)
.backgroundColor(Color.Pink)
.width('100%')
.height('100%')
}
}
Test Results

Perfume Image: Photo by Laura Chouette on Unsplash
Limitations or Considerations
This project is compatible with HarmonyOS Next devices.
Related Documents or Links
https://developer.huawei.com/consumer/en/doc/harmonyos-guides/arkts-routing
Top comments (0)