DEV Community

linzhongxue
linzhongxue

Posted on

Introduction to UniApp Development Based on HarmonyOS Next

Introduction to UniApp Development Based on HarmonyOS Next

With the release of HarmonyOS Next, Huawei has further advanced its all-scenario operating system, offering developers a more unified and efficient development environment. In this context, UniApp has become a key tool for building cross-platform applications. UniApp is a front-end development framework based on Vue.js that allows developers to build applications for multiple platforms using a single codebase, including Android, iOS, Web, and various mini-programs. HarmonyOS Next, as Huawei's new operating system version, is built on the鸿蒙 kernel and adopts a declarative development paradigm, enabling UniApp to seamlessly adapt to its ecosystem and deliver an efficient cross-platform development experience. This article will introduce how to use UniApp and ArkTS for development in HarmonyOS Next, providing detailed code examples and optimization suggestions to help developers quickly get started.

Setting Up the Development Environment

Before beginning development with UniApp on HarmonyOS Next, you need to configure the appropriate development environment. The HarmonyOS ecosystem primarily relies on DevEco Studio, Huawei's official IDE optimized for HarmonyOS application development.

First, visit Huawei's developer website to download and install DevEco Studio. After installation, launch the tool and follow the prompts to configure the SDK. In the SDK Manager, ensure that the SDK version corresponding to HarmonyOS Next is installed to guarantee compatibility. Next, create a new project in DevEco Studio, select HarmonyOS Application, and choose UniApp as the development framework. During project setup, select an appropriate template, such as the blank template or a predefined cross-platform template, and ensure the project language is set to ArkTS.

Once the project is created, configure the emulator. In DevEco Studio's Device Manager, download and install the required HarmonyOS emulator image, and create a virtual device (AVD) to test the application locally. Additionally, ensure that the project supports ArkTS syntax. Check the tsconfig.json or jsconfig.json file to confirm that ArkTS-related compilation options are enabled and that all project dependencies are correctly installed.

Finally, run the project. Click the Run button in DevEco Studio and select the configured emulator or physical device to execute the UniApp application on HarmonyOS. After completing these steps, developers can begin writing ArkTS code and leverage UniApp's cross-platform capabilities for HarmonyOS Next application development.

Basic Syntax of ArkTS and Practical Examples in UniApp

ArkTS is the recommended development language for HarmonyOS Next. It combines the strong typing features of TypeScript with optimizations for the HarmonyOS system, enabling developers to write safer and more efficient code. In UniApp development, ArkTS's basic syntax includes variable declarations, function definitions, and class usage, all of which enhance code readability and maintainability.

Variable Declarations

In ArkTS, variables are declared using let and const, following TypeScript's syntax conventions. For example:

// Define variables
let username: string = "JohnDoe"; // String type
const age: number = 25; // Numeric type

// Type inference
let isLogin = true; // Automatically inferred as boolean
Enter fullscreen mode Exit fullscreen mode

The above code demonstrates how to use type annotations to improve code readability and avoid type-related errors.

Function Definitions

ArkTS supports type-checked functions to ensure correct parameters and return values. For example:

// Define a function that accepts two numeric parameters and returns their sum
function add(a: number, b: number): number {
  return a + b;
}

// Use arrow functions to simplify code
const greet = (name: string): string => {
  return `Hello, ${name}`;
};
Enter fullscreen mode Exit fullscreen mode

By explicitly declaring types, developers can detect potential errors at the compilation stage, improving code quality.

Class Usage

ArkTS supports object-oriented programming, with a syntax similar to TypeScript. For example:

// Define a class
class UserInfo {
  private name: string;
  private age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  // Retrieve user details
  public getDetails(): string {
    return `${this.name} is ${this.age} years old.`;
  }
}

// Create an instance of the class
const user = new UserInfo("John", 25);
console.log(user.getDetails()); // Output: John is 25 years old.
Enter fullscreen mode Exit fullscreen mode

This example demonstrates how to encapsulate data and methods within a class, using access modifiers (e.g., private and public) to control property visibility, improving code encapsulation and security.

In UniApp development, these ArkTS syntax features help developers build robust application logic while ensuring cross-platform consistency.

Core Features of UniApp and ArkTS Code Examples

UniApp provides a range of core features, including page lifecycle management, components, and APIs, which can seamlessly integrate with ArkTS in HarmonyOS Next, allowing developers to build efficient and maintainable applications.

Page Lifecycle

UniApp's page lifecycle enables developers to execute specific logic at different stages, such as page loading, display, hiding, and unloading. In ArkTS, lifecycle hooks like onLoad, onShow, onHide, and onUnload can be used to manage page states. For example:

// Triggered when the page is loaded
onLoad() {
  console.log("Page loaded");
}

// Triggered when the page is displayed
onShow() {
  console.log("Page displayed");
}

// Triggered when the page is hidden
onHide() {
  console.log("Page hidden");
}

// Triggered when the page is unloaded
onUnload() {
  console.log("Page unloaded");
}
Enter fullscreen mode Exit fullscreen mode

These lifecycle functions can be used for data initialization, resource management, and state updates, ensuring that the application behaves correctly at every stage.

Components

UniApp offers a variety of components, such as view, text, image, and button, which can be used to build UI interfaces. In ArkTS, components can be defined using declarative syntax with data binding. For example:

<view class="container">
  <text>{{ message }}</text>
  <button @click="changeMessage">Click to Update Message</button>
</view>
Enter fullscreen mode Exit fullscreen mode
// Page logic
export default {
  data() {
    return {
      message: "Hello HarmonyOS Next"
    };
  },
  methods: {
    changeMessage() {
      this.message = "Message Updated";
    }
  }
};
Enter fullscreen mode Exit fullscreen mode

This example demonstrates how to use UniApp's components in ArkTS with data binding and method calls to implement interactive UI elements.

APIs

UniApp provides a wide range of APIs for accessing device features, such as network requests, local storage, and navigation. These APIs are fully compatible with ArkTS in HarmonyOS Next. For example, using uni.showToast to display a notification:

uni.showToast({
  title: "Operation Successful",
  icon: "success",
  duration: 2000
});
Enter fullscreen mode Exit fullscreen mode

Or using uni.request to make a network call:

uni.request({
  url: "https://api.example.com/data",
  success(res) {
    console.log("Request succeeded", res.data);
  },
  fail(err) {
    console.error("Request failed", err);
  }
});
Enter fullscreen mode Exit fullscreen mode

These core features enable developers to rapidly build fully functional applications while leveraging ArkTS's type safety and HarmonyOS Next's capabilities.

Hands-On Example: Building a Simple Weather Application

To better understand how to develop with UniApp on HarmonyOS Next, let's walk through a complete example by building a simple weather application. This app will allow users to input a city name, fetch its weather data via a network request, and display the results on the screen.

1. Project Creation

First, create a new UniApp project in DevEco Studio and ensure it supports ArkTS syntax. After the project is created, open the pages/index/index.ets file, which will be used to write the main page logic.

2. Page Layout

In the index.ets file, we need to build a simple user interface that includes an input field, a button, and a weather information display area.

<view class="container">
  <input v-model="city" placeholder="Enter city name" />
  <button @click="getWeather">Get Weather</button>
  <view v-if="weatherData">
    <text>City: {{ weatherData.city }}</text>
    <text>Temperature: {{ weatherData.temperature }}°C</text>
    <text>Condition: {{ weatherData.condition }}</text>
  </view>
</view>
Enter fullscreen mode Exit fullscreen mode

Configure the page path in pages.json:

{
  "pages": [
    {
      "path": "pages/index/index",
      "style": {
        "navigationBarTitleText": "Weather App"
      }
    }
  ],
  "globalStyle": {
    "navigationStyle": "custom"
  }
}
Enter fullscreen mode Exit fullscreen mode

3. Implementing the Weather Fetching Logic

Next, write the logic for fetching weather data in index.ets. We will use UniApp's uni.request method to make an API call to a weather service and bind the returned data to the view.

export default {
  data() {
    return {
      city: "",
      weatherData: null
    };
  },
  methods: {
    getWeather() {
      if (!this.city) {
        uni.showToast({
          title: "Please enter a city name",
          icon: "none"
        });
        return;
      }

      // Make network request
      uni.request({
        url: `https://api.example.com/weather?city=${this.city}`,
        success: (res) => {
          if (res.statusCode === 200 && res.data) {
            this.weatherData = res.data;
          } else {
            uni.showToast({
              title: "Failed to fetch weather",
              icon: "none"
            });
          }
        },
        fail: (err) => {
          uni.showToast({
            title: "Network request failed",
            icon: "none"
          });
          console.error(err);
        }
      });
    }
  }
};
Enter fullscreen mode Exit fullscreen mode

4. Running the Application

After completing the code, click the Run button in DevEco Studio and select a configured HarmonyOS emulator or physical device to execute the app. On the emulator, enter a city name and click the button; the application will make a request and display the weather information on the screen.

This example demonstrates the development workflow of UniApp on HarmonyOS Next, including page layout, data binding, and network requests. Developers can further extend this application by adding features such as weather icons, data caching, and location-based weather fetching to enhance functionality and user experience.

Optimization and Enhancement of UniApp on HarmonyOS Next

When developing applications with UniApp on HarmonyOS Next, performance optimization, component reuse, and API usage techniques are key to improving application quality. By adopting appropriate strategies, developers can ensure smooth execution, efficient resource utilization, and an enhanced user experience.

Performance Optimization

To improve application responsiveness and smoothness, consider the following approaches:

  • Reduce unnecessary rendering: In ArkTS, avoid frequent state modifications to minimize page re-rendering. For example, use v-if instead of v-show for conditional rendering to reduce DOM operations.
  • Optimize data loading with local storage: Utilize uni.setStorageSync and uni.getStorageSync to store and retrieve data locally, reducing redundant network requests. For instance, after fetching weather data, cache it and load it first on subsequent page visits.
  • Use animations wisely: Avoid excessive complex animations to reduce page lag. Use transition and animation attributes to optimize animations while ensuring they do not block the main thread.

Component Reuse

Component reuse enhances development efficiency and maintainability:

  • Custom components: Encapsulate frequently used UI elements as custom components, such as weather cards, buttons, and input fields, to improve code maintainability. For example:
// Custom weather card component
@Component
struct WeatherCard {
  @Prop city: string;
  @Prop temperature: number;
  @Prop condition: string;

  build() {
    Column() {
      Text(`City: ${this.city}`)
      Text(`Temperature: ${this.temperature}°C`)
      Text(`Condition: ${this.condition}`)
    }
  }
}
Enter fullscreen mode Exit fullscreen mode
  • Lazy loading of components: Use uni.preloadPages to preload subsequent pages, improving the smoothness of page transitions.

API Usage Techniques

Proper utilization of UniApp's APIs enhances application functionality and stability:

  • Optimize network requests: When using uni.request, set appropriate timeout and retry mechanisms to avoid unresponsive applications due to network fluctuations. For example, implement debounce or throttle strategies to reduce duplicate requests.
  • Handle errors gracefully: Provide user-friendly error messages when API calls fail and log errors for debugging. For instance, use uni.showToast alongside console.error to deliver feedback.
  • Manage permissions effectively: Before calling APIs requiring permissions (e.g., location, camera), check and request the necessary permissions to ensure smooth application execution.

By applying these optimization strategies, developers can build more efficient and stable UniApp applications on HarmonyOS Next, enhancing both development experience and application performance.

Top comments (0)