旅行记录应用编辑旅行 - Cordova & OpenHarmony 混合开发实战
本文介绍了开源鸿蒙跨平台开发中的旅行编辑功能实现方案。该功能允许用户修改已创建的旅行记录,包括目的地、日期、花费等所有信息。编辑流程分为三个步骤:数据加载与表单填充、数据更新与版本记录、原生层冲突处理。文章提供了Web端代码实现,包括HTML表单结构、旅行数据加载函数和更新函数。更新函数会记录修改内容并保存编辑历史,支持版本控制。该功能采用Cordova与OpenHarmony混合开发框架,可实现
欢迎大家加入开源鸿蒙跨平台开发者社区,一起共建开源鸿蒙跨平台生态。
📌 概述
编辑旅行功能允许用户修改已创建的旅行记录。用户可以编辑旅行的所有信息,包括目的地、日期、花费、描述、标签、同行者等。编辑功能需要支持版本控制,记录编辑历史。在 Cordova 与 OpenHarmony 的混合开发框架中,编辑旅行需要实现数据加载、表单更新和版本管理。
🔗 完整流程
第一步:旅行数据加载与表单填充
编辑旅行页面需要从数据库中加载旅行数据,然后填充到表单中。表单需要显示旅行的所有信息,用户可以修改任何字段。
第二步:数据更新与版本记录
当用户修改旅行数据时,需要更新数据库中的记录,并记录编辑历史。编辑历史包括编辑时间、编辑人、修改内容等信息。
第三步:原生层编辑冲突处理与同步
OpenHarmony 原生层可以处理编辑冲突,当多个用户同时编辑同一条记录时,原生层可以进行冲突检测和解决。
🔧 Web 代码实现
编辑旅行页面 HTML 结构
<div id="edit-trip-page" class="page">
<div class="page-header">
<h1>编辑旅行</h1>
</div>
<form id="editTripForm" class="trip-form">
<div class="form-group">
<label>目的地 *</label>
<input type="text" name="destination" required placeholder="输入目的地...">
</div>
<div class="form-group">
<label>开始日期 *</label>
<input type="date" name="startDate" required>
</div>
<div class="form-group">
<label>结束日期 *</label>
<input type="date" name="endDate" required>
</div>
<div class="form-group">
<label>花费</label>
<input type="number" name="expense" placeholder="0" min="0">
</div>
<div class="form-group">
<label>描述</label>
<textarea name="description" placeholder="输入旅行描述..."></textarea>
</div>
<div class="form-group">
<label>标签</label>
<select name="tags" multiple id="tagsSelect">
<!-- 标签选项动态加载 -->
</select>
</div>
<div class="form-actions">
<button type="button" class="btn btn-primary" onclick="updateTrip()">
保存
</button>
<button type="button" class="btn btn-secondary" onclick="navigateTo('trip-detail')">
取消
</button>
</div>
</form>
</div>
HTML 结构与新建旅行类似,但用于编辑已有的旅行。
加载旅行数据函数
async function loadTripForEdit(tripId) {
try {
// 从数据库获取旅行数据
const trip = await db.getTrip(tripId);
if (!trip) {
showToast('旅行不存在');
navigateTo('all-trips');
return;
}
// 填充表单
const form = document.getElementById('editTripForm');
form.querySelector('input[name="destination"]').value = trip.destination;
form.querySelector('input[name="startDate"]').value = trip.startDate;
form.querySelector('input[name="endDate"]').value = trip.endDate;
form.querySelector('input[name="expense"]').value = trip.expense || 0;
form.querySelector('textarea[name="description"]').value = trip.description || '';
// 选中标签
const tagsSelect = form.querySelector('select[name="tags"]');
if (trip.tags) {
Array.from(tagsSelect.options).forEach(option => {
option.selected = trip.tags.includes(parseInt(option.value));
});
}
// 存储原始数据用于比较
window.originalTrip = JSON.parse(JSON.stringify(trip));
} catch (error) {
console.error('Error loading trip:', error);
showToast('加载旅行失败');
}
}
加载函数从数据库获取旅行数据,然后填充到表单中。loadTripForEdit 函数是编辑旅行的初始化函数。函数首先从数据库获取要编辑的旅行数据。如果旅行不存在,则显示错误提示并导航回全部旅行页面。如果旅行存在,函数将旅行的所有信息填充到编辑表单中,包括目的地、日期、花费、描述等。对于标签字段,函数需要遍历所有标签选项,将旅行中包含的标签标记为已选中。最后,函数将原始旅行数据保存到全局变量中,用于后续的编辑历史记录。通过这个函数,用户可以看到旅行的完整信息,并进行编辑。
更新旅行函数
async function updateTrip() {
// 验证表单
if (!validateTripForm()) {
return;
}
try {
// 获取表单数据
const form = document.getElementById('editTripForm');
const formData = new FormData(form);
// 获取原始旅行数据
const trip = window.originalTrip;
// 记录修改内容
const changes = [];
if (trip.destination !== formData.get('destination')) {
changes.push(`目的地: ${trip.destination} → ${formData.get('destination')}`);
trip.destination = formData.get('destination');
}
if (trip.startDate !== formData.get('startDate')) {
changes.push(`开始日期: ${trip.startDate} → ${formData.get('startDate')}`);
trip.startDate = formData.get('startDate');
}
if (trip.endDate !== formData.get('endDate')) {
changes.push(`结束日期: ${trip.endDate} → ${formData.get('endDate')}`);
trip.endDate = formData.get('endDate');
}
// 更新其他字段
trip.expense = parseInt(formData.get('expense')) || 0;
trip.description = formData.get('description');
trip.tags = formData.getAll('tags');
trip.updatedAt = new Date().toISOString();
// 保存到数据库
await db.updateTrip(trip);
// 记录编辑历史
if (changes.length > 0) {
const history = {
id: Date.now(),
tripId: trip.id,
changes: changes,
timestamp: trip.updatedAt
};
await db.addEditHistory(history);
}
showToast('旅行已更新');
// 导航回旅行详情页面
navigateTo('trip-detail', trip.id);
// 通知原生层
if (window.cordova) {
cordova.exec(
(result) => console.log('Trip updated:', result),
(error) => console.error('Update error:', error),
'TripPlugin',
'onTripUpdated',
[{ tripId: trip.id, changeCount: changes.length, timestamp: Date.now() }]
);
}
} catch (error) {
console.error('Error updating trip:', error);
showToast('更新失败,请重试');
}
}
更新函数记录修改内容,然后保存到数据库。
编辑历史记录函数
async function loadEditHistory(tripId) {
try {
// 从数据库获取编辑历史
const history = await db.getEditHistory(tripId);
// 按时间倒序排序
history.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
// 渲染编辑历史
renderEditHistory(history);
} catch (error) {
console.error('Error loading edit history:', error);
}
}
编辑历史加载函数从数据库获取编辑历史。
编辑历史渲染函数
function renderEditHistory(history) {
const container = document.getElementById('editHistory');
if (!container) return;
container.innerHTML = '';
history.forEach(record => {
const historyElement = document.createElement('div');
historyElement.className = 'history-item';
historyElement.innerHTML = `
<div class="history-header">
<span class="history-time">${formatDate(record.timestamp)}</span>
</div>
<div class="history-body">
<ul class="changes-list">
${record.changes.map(change => `<li>${change}</li>`).join('')}
</ul>
</div>
`;
container.appendChild(historyElement);
});
}
编辑历史渲染函数展示编辑历史列表。
🔌 OpenHarmony 原生代码实现
旅行更新插件
// TripPlugin.ets
export class TripPlugin {
// 处理旅行更新事件
onTripUpdated(args: any, callback: Function): void {
try {
const tripId = args[0].tripId;
const changeCount = args[0].changeCount;
const timestamp = args[0].timestamp;
console.log(`[Trip] Updated: ${tripId}, Changes: ${changeCount}`);
callback({ success: true, message: '旅行已更新' });
} catch (error) {
callback({ success: false, error: error.message });
}
}
}
旅行更新插件处理旅行更新事件。
📝 总结
编辑旅行功能展示了如何在 Cordova 与 OpenHarmony 框架中实现一个完整的数据编辑系统。Web 层负责表单 UI 和编辑历史记录,原生层负责数据同步。通过编辑历史,用户可以追踪旅行信息的修改过程。
更多推荐




所有评论(0)