DEV Community

linzhongxue
linzhongxue

Posted on

Practical Guide to UniApp Development Based on HarmonyOS Next

Practical Guide to UniApp Development Based on HarmonyOS Next

Preface

With the release of HarmonyOS Next, the developer ecosystem has ushered in new opportunities. As a cross-platform development framework, UniApp is highly favored by developers for its "write once, run anywhere" capability. This article provides a detailed introduction to developing applications with UniApp in the HarmonyOS Next environment, covering basic setup, core feature implementation, and practical case demonstrations.

1. Environment Setup and Project Creation

1.1 Development Environment Configuration

Before starting UniApp development for HarmonyOS Next, ensure your development environment meets the following requirements:

  1. Install the latest version of DevEco Studio (recommended version 4.0 or higher).
  2. Configure the Node.js environment (recommended version 16.x LTS).
  3. Install the UniApp plugin (via HBuilderX or direct integration).
# Check Node.js version  
node -v  
# Check npm version  
npm -v  
Enter fullscreen mode Exit fullscreen mode

1.2 Creating a UniApp Project

Follow these steps to create a UniApp project in DevEco Studio:

  1. Select File → New → Project.
  2. Choose UniApp from the template list.
  3. Configure the project name, package name, and storage path.
  4. Click Finish to complete the creation.

After project creation, you will see the standard UniApp directory structure:

├── common                # Public resources  
├── components            # Custom components  
├── pages                 # Pages directory  
├── static                # Static resources  
├── manifest.json         # App configuration  
├── pages.json            # Page routing configuration  
└── uni.scss              # Global styles  
Enter fullscreen mode Exit fullscreen mode

2. Integrated Development with ArkTS and UniApp

2.1 Basic ArkTS Syntax

ArkTS is the recommended development language for HarmonyOS Next. It extends TypeScript and provides better type checking and performance optimization.

// Define a simple ArkTS component  
@Component  
struct MyComponent {  
  // State variable  
  @State message: string = 'Hello HarmonyOS'  

  // Build UI  
  build() {  
    Column() {  
      Text(this.message)  
        .fontSize(20)  
        .fontColor(Color.Blue)  

      Button('Click Me')  
        .onClick(() => {  
          this.message = 'You clicked the button!'  
        })  
    }  
    .width('100%')  
    .height('100%')  
    .justifyContent(FlexAlign.Center)  
  }  
}  
Enter fullscreen mode Exit fullscreen mode

2.2 Interaction Between UniApp Pages and ArkTS

In UniApp, we can integrate ArkTS components into pages as follows:

// pages/index/index.uvue  
<template>  
  <view class="container">  
    <!-- Reference ArkTS component -->  
    <my-component />  
  </view>  
</template>  

<script lang="uts">  
import { MyComponent } from '../../components/MyComponent'  

export default {  
  components: {  
    MyComponent  
  },  
  data() {  
    return {  
      title: 'UniApp on HarmonyOS'  
    }  
  }  
}  
</script>  

<style>  
.container {  
  flex-direction: column;  
  justify-content: center;  
  align-items: center;  
  width: 100%;  
  height: 100%;  
}  
</style>  
Enter fullscreen mode Exit fullscreen mode

3. Core Feature Implementation

3.1 Page Routing and Navigation

UniApp retains its routing system in HarmonyOS Next while leveraging ArkTS navigation for smoother transitions.

// Example of page navigation  
uni.navigateTo({  
  url: '/pages/detail/detail?id=123'  
})  

// Receiving parameters  
// pages/detail/detail.uvue  
<script lang="uts">  
export default {  
  onLoad(options: any) {  
    console.log('Received parameter:', options.id)  
  }  
}  
</script>  
Enter fullscreen mode Exit fullscreen mode

3.2 Data Storage and Management

HarmonyOS Next offers multiple data storage solutions compatible with UniApp APIs:

// Using local storage  
uni.setStorage({  
  key: 'userInfo',  
  data: {  
    name: 'John Doe',  
    age: 25  
  },  
  success: () => {  
    console.log('Storage successful')  
  }  
})  

// Retrieving data  
uni.getStorage({  
  key: 'userInfo',  
  success: (res) => {  
    console.log('Retrieved data:', res.data)  
  }  
})  
Enter fullscreen mode Exit fullscreen mode

3.3 Network Requests

UniApp’s network request APIs remain functional in HarmonyOS Next:

uni.request({  
  url: 'https://api.example.com/data',  
  method: 'GET',  
  success: (res) => {  
    console.log('Request successful:', res.data)  
  },  
  fail: (err) => {  
    console.error('Request failed:', err)  
  }  
})  
Enter fullscreen mode Exit fullscreen mode

4. UI Component Development in Practice

4.1 Custom ArkTS Components

Below is an example of a custom button component combining UniApp and ArkTS:

// components/CustomButton.ets  
@Component  
export struct CustomButton {  
  // External parameters  
  @Prop text: string = 'Button'  
  @Prop color: string = '#007AFF'  

  // Define event  
  private onClick: () => void = () => {}  

  build() {  
    Button(this.text)  
      .width(200)  
      .height(50)  
      .fontSize(16)  
      .fontColor(Color.White)  
      .backgroundColor(this.color)  
      .borderRadius(25)  
      .onClick(() => {  
        this.onClick()  
      })  
  }  
}  
Enter fullscreen mode Exit fullscreen mode

Using this component in a UniApp page:

// pages/home/home.uvue  
<template>  
  <view>  
    <custom-button   
      text="Login"   
      color="#FF5722"   
      @onClick="handleLogin"   
    />  
  </view>  
</template>  

<script lang="uts">  
import { CustomButton } from '../../components/CustomButton'  

export default {  
  components: {  
    CustomButton  
  },  
  methods: {  
    handleLogin() {  
      console.log('Login button clicked')  
      uni.showToast({  
        title: 'Logging in...',  
        icon: 'loading'  
      })  
    }  
  }  
}  
</script>  
Enter fullscreen mode Exit fullscreen mode

4.2 List Rendering and Performance Optimization

For HarmonyOS Next, list rendering requires special attention to performance:

// pages/list/list.uvue  
<template>  
  <view>  
    <list class="item-list">  
      <list-item   
        v-for="(item, index) in items"   
        :key="index"   
        type="item"  
      >  
        <text>{{ item.name }}</text>  
      </list-item>  
    </list>  
  </view>  
</template>  

<script lang="uts">  
export default {  
  data() {  
    return {  
      items: Array.from({ length: 100 }, (_, i) => ({  
        id: i + 1,  
        name: `Item ${i + 1}`  
      }))  
    }  
  }  
}  
</script>  

<style>  
.item-list {  
  width: 100%;  
  height: 100%;  
}  
</style>  
Enter fullscreen mode Exit fullscreen mode

5. Accessing Device Capabilities

5.1 Using System Features

HarmonyOS Next provides rich system capabilities accessible via UniApp APIs:

// Get device information  
uni.getSystemInfo({  
  success: (res) => {  
    console.log('Device brand:', res.brand)  
    console.log('OS:', res.osName)  
    console.log('Screen width:', res.screenWidth)  
  }  
})  

// Access camera  
uni.chooseImage({  
  count: 1,  
  sourceType: ['camera'],  
  success: (res) => {  
    console.log('Image path:', res.tempFilePaths[0])  
  }  
})  
Enter fullscreen mode Exit fullscreen mode

5.2 Leveraging HarmonyOS-Specific Features

Extended APIs enable the use of HarmonyOS Next’s unique capabilities:

// Use distributed capabilities  
uni.requireNativePlugin('distributed').getDevices({  
  success: (devices) => {  
    console.log('Nearby devices:', devices)  
  }  
})  

// Use atomic services  
uni.requireNativePlugin('ability').startAbility({  
  bundleName: 'com.example.service',  
  abilityName: 'MainAbility',  
  success: () => {  
    console.log('Service started successfully')  
  }  
})  
Enter fullscreen mode Exit fullscreen mode

6. Debugging and Publishing

6.1 Debugging Tips

Debugging methods for UniApp projects in DevEco Studio:

  1. Use logging: console.log(), uni.showToast()
  2. Set breakpoints in ArkTS code
  3. Performance analysis with DevEco Studio’s profiling tools

6.2 App Packaging and Release

Steps to package a UniApp project into a HarmonyOS app:

  1. Select Build → Build HAP in DevEco Studio
  2. Configure signing information (create a signing certificate for first-time builds)
  3. Wait for the build to complete and obtain the .hap file
  4. Submit for review via AppGallery Connect

7. Comprehensive Case Study: Weather Forecast App

This section demonstrates a complete weather forecast application built with UniApp on HarmonyOS Next.

7.1 Project Structure

weather-app/  
├── common/  
│   ├── icons.ets       # Weather icon components  
│   └── api.ts          # API wrappers  
├── components/  
│   ├── WeatherCard.ets # Weather card  
│   └── CityPicker.ets  # City picker  
├── pages/  
│   ├── index/          # Home page  
│   └── detail/         # Details page  
└── static/             # Static resources  
Enter fullscreen mode Exit fullscreen mode

7.2 Core Code Implementation

Weather Card Component

// components/WeatherCard.ets  
@Component  
export struct WeatherCard {  
  @Prop weatherData: WeatherData  

  build() {  
    Column() {  
      Text(this.weatherData.city)  
        .fontSize(24)  
        .fontWeight(FontWeight.Bold)  

      Row() {  
        Image(this.getWeatherIcon())  
          .width(60)  
          .height(60)  

        Column() {  
          Text(`${this.weatherData.temp}°C`)  
            .fontSize(36)  
          Text(this.weatherData.condition)  
            .fontSize(16)  
        }  
      }  

      // More weather info...  
    }  
    .padding(20)  
    .borderRadius(10)  
    .backgroundColor('#FFFFFF')  
    .shadow({ radius: 10, color: '#000000', offsetX: 0, offsetY: 2 })  
  }  

  private getWeatherIcon(): string {  
    // Return icon based on weather condition  
    return `/static/${this.weatherData.condition}.png`  
  }  
}  

interface WeatherData {  
  city: string  
  temp: number  
  condition: string  
  // Other fields...  
}  
Enter fullscreen mode Exit fullscreen mode

Main Page Implementation

// pages/index/index.uvue  
<template>  
  <view class="container">  
    <city-picker @change="fetchWeatherData" />  

    <weather-card :weather-data="currentWeather" />  

    <list class="forecast-list">  
      <list-item   
        v-for="(item, index) in forecast"   
        :key="index"  
      >  
        <forecast-item :data="item" />  
      </list-item>  
    </list>  
  </view>  
</template>  

<script lang="uts">  
import { WeatherCard } from '../../components/WeatherCard'  
import { CityPicker } from '../../components/CityPicker'  
import { ForecastItem } from '../../components/ForecastItem'  
import { getWeather } from '../../common/api'  

export default {  
  components: {  
    WeatherCard,  
    CityPicker,  
    ForecastItem  
  },  
  data() {  
    return {  
      currentWeather: {},  
      forecast: []  
    }  
  },  
  methods: {  
    async fetchWeatherData(city: string) {  
      try {  
        const data = await getWeather(city)  
        this.currentWeather = data.current  
        this.forecast = data.forecast  
      } catch (error) {  
        uni.showToast({  
          title: 'Failed to fetch weather',  
          icon: 'none'  
        })  
      }  
    }  
  },  
  onLoad() {  
    this.fetchWeatherData('Beijing')  
  }  
}  
</script>  

<style>  
.container {  
  padding: 20px;  
}  
.forecast-list {  
  margin-top: 20px;  
}  
</style>  
Enter fullscreen mode Exit fullscreen mode

8. Performance Optimization Recommendations

  1. Minimize unnecessary renders: Use @State and @Prop to manage component states effectively.
  2. List optimization: Use <list> and <list-item> components for long lists.
  3. Image handling: Compress images and use appropriate formats.
  4. Code splitting: Configure subpackage loading for large applications.
  5. On-demand imports: Only import necessary components and APIs.

9. Frequently Asked Questions

Q1: How compatible is UniApp with HarmonyOS Next?

A1: UniApp has been adapted for HarmonyOS Next, and most features work well. For HarmonyOS-specific capabilities, use extended APIs or native plugins.

Q2: How to resolve styling issues?

A2: HarmonyOS Next uses its own rendering engine, so some CSS properties may not be supported. Use ArkTS styling or check UniApp’s supported style list.

Q3: Can we directly call HarmonyOS Native APIs?

A3: Yes, use uni.requireNativePlugin to access native capabilities or develop custom native plugins.

Conclusion

By following this guide, you should now understand the fundamentals of developing applications with UniApp in the HarmonyOS Next environment. The cross-platform nature of UniApp combined with the powerful capabilities of HarmonyOS Next opens up new possibilities for developers. As technology evolves, we can expect more innovative applications to emerge in this ecosystem.

Top comments (0)