Hướng dẫn phát triển ứng dụng Mini Program trên nền tảng WeChat

Cơ bản về Mini Program

Thanh điều hướng (Navigation Bar)

1. Tùy chỉnh thanh điều hướng

Trong file app.json, thiết lập:

"window": {
  "navigationStyle": "custom"
}

Sử dụng component tùy chỉnh trong trang cụ thể:

{
  "usingComponents": {
    "custom-nav": "/components/custom-nav/custom-nav"
  }
}

Trong WXML:

<custom-nav title="Cài đặt" showBack="{{true}}" textColor="black" bgColor="#FFF"></custom-nav>

Hoặc sử dụng phiên bản từ thư viện WeUI:

{
  "usingComponents": {
    "mp-navigation-bar": "/miniprogram_npm/weui-miniprogram/navigation-bar/navigation-bar"
  }
}
<mp-navigation-bar title="Thư viện sách" showBack="{{false}}"></mp-navigation-bar>

2. Sử dụng thanh điều hướng mặc định

Xóa thuộc tính navigationStyle: "custom" trong app.json. Thiết lập tiêu đề trong file JSON của từng trang:

{
  "navigationBarTitleText": "Trang chủ"
}

TabBar

Cấu hình trong app.json:

"tabBar": {
  "color": "#7A7E83",
  "selectedColor": "#3589ff",
  "backgroundColor": "#F7F7F7",
  "list": [
    {
      "pagePath": "pages/home/home",
      "text": "Trang chủ",
      "iconPath": "/assets/icons/home.png",
      "selectedIconPath": "/assets/icons/home-active.png"
    },
    {
      "pagePath": "pages/category/category",
      "text": "Danh mục",
      "iconPath": "/assets/icons/category.png",
      "selectedIconPath": "/assets/icons/category-active.png"
    }
  ]
}

Lưu trữ dữ liệu cục bộ

wx.setStorageSync('bookTypes', [
  { id: 1, name: 'Sách tranh', price: 5 },
  { id: 2, name: 'Tiểu thuyết', price: 4 }
]);

const storedData = wx.getStorageSync('bookTypes');
console.log(storedData);

Component input

<input placeholder="Tìm kiếm..." value="{{searchQuery}}" confirm-type="search" bindconfirm="onSearchSubmit" />
onSearchSubmit(e) {
  console.log('Giá trị tìm kiếm:', e.detail.value);
}

Swiper (carousel)

<swiper indicator-dots autoplay interval="2000" duration="500">
  <block wx:for="{{slideImages}}" wx:key="id">
    <swiper-item>
      <image src="{{item.url}}" mode="widthFix" />
    </swiper-item>
  </block>
</swiper>

Scroll View

Cuộn dọc với kéo xuống làm mới:

<scroll-view scroll-y refresher-enabled bindrefresherrefresh="onRefresh" refresher-triggered="{{refreshing}}" style="height: 300px">
  <view wx:for="{{items}}">{{item}}</view>
</scroll-view>
onRefresh() {
  setTimeout(() => {
    this.setData({ refreshing: false });
    wx.showToast({ title: 'Đã làm mới' });
  }, 1000);
}

Cuộn ngang:

<scroll-view scroll-x class="horizontal-scroll">
  <view class="item" wx:for="{{tags}}">{{item}}</view>
</scroll-view>
.horizontal-scroll {
  display: flex;
  white-space: nowrap;
}
.item {
  display: inline-block;
  padding: 10rpx 20rpx;
}

Switch

<switch checked="{{darkMode}}" bindchange="toggleTheme" />
toggleTheme(e) {
  this.setData({ darkMode: e.detail.value });
}

Checkbox Group

<checkbox-group bindchange="onSelectionChange">
  <label wx:for="{{options}}">
    <checkbox value="{{item.id}}" checked="{{item.selected}}" /> {{item.label}}
  </label>
</checkbox-group>
onSelectionChange(e) {
  const selectedIds = e.detail.value.map(id => parseInt(id));
  const updatedOptions = this.data.options.map(opt => ({
    ...opt,
    selected: selectedIds.includes(opt.id)
  }));
  this.setData({ options: updatedOptions });
}

Render danh sách với wx:for

<view wx:for="{{books}}" wx:for-item="book" wx:for-index="idx" wx:key="id">
  {{idx + 1}}. {{book.title}}
</view>

Điều hướng giữa các trang

<navigator url="/pages/detail/detail?id=123" open-type="navigate">Xem chi tiết</navigator>

Với tab đã khai báo trong tabBar, dùng:

wx.switchTab({ url: '/pages/home/home' });

hoặc trong WXML:

<navigator url="/pages/home/home" open-type="switchTab">Về trang chủ</navigator>

Cơ bản JavaScript cho Mini Program

Thao tác mảng và JSON

Chuyển đổi JSON:

const rawData = [{ id: 1, name: 'Sách A' }];
const jsonString = JSON.stringify(rawData);
const parsedArray = JSON.parse(jsonString);

Lấy tên từ mảng đối tượng:

const names = books.map(book => book.name);

Định dạng lại dữ liệu:

const formattedBooks = books.map(book => ({
  ...book,
  displayPrice: `₫${book.price.toLocaleString()}`
}));

Lọc dữ liệu:

const expensiveBooks = books.filter(book => book.price >= 50000);

Giải cấu trúc và sao chép nông

const clonedList = [...this.data.originalList]; // Sao chép nông

Tạo dữ liệu ngẫu nhiên

Thuật toán xáo bài (Fisher-Yates):

function shuffleAndPick(arr, count) {
  const copy = [...arr];
  for (let i = copy.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [copy[i], copy[j]] = [copy[j], copy[i]];
  }
  return copy.slice(0, count);
}

Chọn ngẫu nhiên không trùng lặp:

function getRandomUnique(arr, num) {
  const result = [];
  const usedIndices = new Set();
  while (result.length < num && usedIndices.size < arr.length) {
    const idx = Math.floor(Math.random() * arr.length);
    if (!usedIndices.has(idx)) {
      usedIndices.add(idx);
      result.push(arr[idx]);
    }
  }
  return result;
}

CSS với Flexbox trong Mini Program

Bố cục cơ bản với Flex

Hai cột đều nhau:

.container {
  display: flex;
  justify-content: space-between;
}
.left, .right {
  width: 48%;
}

Cột trái cố định, phải co dãn:

.container {
  display: flex;
}
.left {
  width: 200rpx;
}
.right {
  flex: 1;
}

Tỷ lệ 2:5:

.left { flex: 2; }
.right { flex: 5; }

Dàn hàng tự động (2 hàng):

.grid {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}
.item {
  width: calc(50% - 10rpx);
}

Căn giữa theo chiều dọc và ngang:

.center-box {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

Tích hợp WeUI

Cài đặt WeUI

Qua npm (offline):

npm install weui-miniprogram --save-prod

Sau khi build, import vào dự án:

/* app.wxss */
@import '/miniprogram_npm/weui-miniprogram/weui-wxss/dist/style/weui.wxss';
/* Trang JSON */
{
  "usingComponents": {
    "mp-button": "/miniprogram_npm/weui-miniprogram/button/button"
  }
}

Từ mã nguồn Git:

git clone https://gitcode.com/weui-miniprogram.git
cd weui-miniprogram
npm install
npm run build

Sau đó copy thư mục dist vào dự án và import tương tự.

Thẻ: WeChat miniprogram weui flexbox JavaScript

Đăng vào ngày 1 tháng 7 lúc 16:33