167
社区成员
目录
5.Description of design and implementation process
The purpose of this assignment is to learn to complete an address book development task with front to back interaction. I choose to use wechat mini program development tool to complete this project. In the small program development software, the front-end page can be directly compiled, while the back-end function is written, the data set and cloud function are deployed on the cloud server of wechat small program, and the interaction between the front and back end can be realized by calling the cloud function at the small program development end. The system contains three pages for creating contacts and contact directory contact details. However, due to the influence of market regulation, the content of the small program is suspected of collecting the privacy of others, so it can not pass the audit and release. Therefore, the following blog does not provide links to use, and provides a demonstration of relevant functions
This table shows the basic information of the project and my personal information
Course for This Assignment | 2401_MU_SE_EE308 |
---|---|
Student ID | FZU:832201119 MU:22125353 |
Assignment Requirements | Design a front-end and back-end separated contact |
Objectives of This Assignment | Exercise independent learning ability and learn the basic knowledge of software development |
Here are the front-end and back-end code provided in GitHub, you can click on the link to view
This is the corresponding front-end code:前端的文本(总体)
This is the back end (cloud function):后端的文本(.js为主)
This is a PSP table showing my expected planned time and actual time for each task at the beginning of the project
Phase | Estimated Time (hours) | Actual Time (hours) |
Requirements Analysis | 1 | 1 |
Design | 3 | 4 |
Frontend Development | 3 | 3 |
Backend Development | 5 | 8 |
Testing | 5 | 8 |
Deployment and Presentation | 3 | 5 |
Total | 20 | 29 |
Add a contact, and then check it
View and modify existing contact information
One-click delete function
Interactive viewing of back-end (cloud) information
The front end gets information and uploads it to the back end in real time
Including deletion, the information is also immediately reflected in the database
These are the basic functions.
The diagram shows the framework of my entire project, which includes the cloud function file, the main file (contact details, contact directory and creating contacts (index)), and the global app file.
The Cloud Functions folder contains four modules: addContact,deleteContact,getContacts and modifyContact. Each corresponds to the four functions of their nameBecause the basic framework of these four functions is similar, the determination of the cloud function entry file and the setting of the cloud function entry function constitute the main part. Therefore, for one of the contents, addContact is explained here.
const cloud = require('wx-server-sdk'); : Introduce the cloud development SDK of wechat mini program for connecting to the database.
cloud.init(); Initialize the cloud environment so that cloud functions can call databases and other cloud resources.
const db = cloud.database(); : Creates a database instance db for subsequent database operations.
exports.main = async (event, context) => {... } : Defines the entrance to the cloud function. const { name, phone } = event; : Deconstructs the event parameter from the front end and extracts the name and phone fields.
await db.collection('contacts').add(...) : Adds a new record to the contacts collection. data: {name, phone} : Specifies the content of the record, including name and phone number. return { success: true }; : If the record is successfully added, success: true is returned. catch an exception in a catch statement, print an error, and return success: false with an error message.
For the other three cloud functions, the functions of function initialization, data collection and return are consistent, with only some small differences in individual functions, not much explanation
The next step is to explain the design of the contacts page (index page)
In index.wxml
The <view class="container">
serves as the main wrapper, organizing the entire page layout. Each <view class="input-group">
represents a section for a specific piece of contact information, such as surname, given name, and phone number. Inside each input-group
, there’s a <text class="label">
for the field name (like "Last Name") and an <input>
element where users enter data. The placeholder
attribute in <input>
displays a hint when the field is empty, and bindinput
triggers JavaScript functions (e.g., onLastNameInput
) to capture input in real-time, ensuring that the values entered by users are stored in the page’s data model.
The value="{{lastName}}"
(or firstName
, phone
) binds each field to a specific data property, so changes are immediately reflected in the UI and data model. This two-way binding is crucial for dynamic updates.
Finally, the <button class="save-btn" bindtap="saveContact">
element serves as the submit button. The bindtap
attribute links the button to the saveContact
function, which executes when the button is tapped. This function will typically send the input data to a cloud database, completing the data entry process and updating the contact list.
In index.json
"navigationBarTitleText"
: This sets the title of the navigation bar at the top of the page, such as "Contact List"
or "Add Contact"
. It’s displayed to users and helps them understand the current page context.
"enablePullDownRefresh"
(optional): Enables the pull-down-to-refresh action, which is useful if the page displays dynamic data like a contact list that may need refreshing.
"navigationBarBackgroundColor"
and "navigationBarTextStyle"
(optional): These set the background color and text style of the navigation bar, often configured to improve readability and match the app’s theme.
In index.js
const db = wx.cloud.database();
: Initializes the cloud database instance db
, allowing this page to interact with the cloud database, such as adding or querying records
data
: Defines the initial state of the page’s data properties, including:
avatarUrl
: Stores the path for the avatar image.lastName
, firstName
, phone
, email
: Stores contact details to be input by the user
chooseAvatar
function: Opens an image picker dialog to select a profile picture.
count: 1
: Limits selection to one image.sizeType: ['compressed']
: Requests a compressed image for faster upload.sourceType: ['album', 'camera']
: Allows choosing from the photo album or taking a new photo.success: res => {...}
: After the image is chosen, retrieves its local path (res.tempFilePaths[0]
) and updates avatarUrl
in data
.
saveContact
function: Saves the contact information, including avatar, to the database.
Data extraction: Uses destructuring to access avatarUrl
, lastName
, firstName
, phone
, and email
from data
.Database operation:fail
callback: If saving fails, shows an error message with wx.showToast
.success
callback: Shows a success message with wx.showToast
and navigates back to the previous page.data
: Specifies the fields to store, mapping avatarUrl
, lastName
, firstName
, phone
, and email
. db.collection('contacts').add({...})
: Adds a new contact record to the contacts
collection.
In index.wxss
.container
: Sets overall padding and layout for the page, creating space around the elements and centering the content.
.input-group
: Defines styling for each input section, including padding and alignment. It likely adds spacing between input fields and border separators for visual clarity.
.label
: The class for <text>
elements that label each field (e.g., "Last Name" or "Phone Number"). This style may include font size, weight, color, and width adjustments for consistency.
.input
: Styles the input fields themselves. This might include font size, color, padding, and potentially a border or background color to visually separate the fields.
.save-btn
: Styles the save button, setting background color (e.g., blue for prominence), text color (usually white), padding, border-radius for rounded edges, and alignment. It ensures the button stands out and is easy to click.
.delete-btn
(if present): Applies a similar style to the save button but with a different color (often red) to indicate caution. This class styles the delete button in the detail page.
The above completes the explanation of the code in the index folder, in order to keep the blog as simple as possible, please go to github to see the detailed code.
Next, I will continue to explain the Contact page and the contactDetail page. As for the wxss page, because the content is very similar to index.wxss, I will pay more attention to the explanation of.js and.ml files
contact.wxml
Outer Container (<view class="container">
):
Wraps the entire contact list interface, setting up a consistent structure and applying styling for layout.
Title Section (<view class="header">
):
Displays a fixed title, “牢6的通讯录,” at the top of the page using a <text class="title">
element. This serves as a header to provide context for the page.
Contact List Block (<block wx:for="{{contacts}}" wx:key="id">
):
Loops over the contacts
data array, rendering each contact’s information. The wx:for
directive iterates through contacts
, with wx:key="id"
ensuring that each item is uniquely identified by id
, improving rendering performance.
Contact Item (<view class="contact-item">
):
Represents each contact entry in the list, with two key elements:Contact Name (<text class="contact-name">{{item.fullName}}</text>
): Displays the full name of the contact, extracted from item.fullName
within the contacts
array.Details Button (<button class="detail-button" bindtap="goToContactDetail" data-id="{{item._id}}">查看详情</button>
): Adds a button labeled "查看详情" ("View Details") on the right side of each contact. The button triggers the goToContactDetail
function when tapped, passing the contact’s unique _id
as a data-id
attribute, which helps identify the specific contact.
Divider (<view class="divider"></view>
):
A styled separator line that visually separates each contact in the list, providing a clear distinction between entries for improved readability.
contact.js
Initialize Database:
const db = wx.cloud.database();
initializes a connection to the cloud database, allowing interaction with collections (in this case, contacts
).
Data Object:
data: { contacts: [] }
initializes an empty contacts
array to store contact data fetched from the database.
onShow()
Function:
Called each time the page is shown, it invokes getContactsFromDB()
to refresh contact data.
getContactsFromDB()
Function:
Fetches all documents from the contacts
collection and maps each contact, adding a fullName
property combining lastName
and firstName
. It then updates contacts
in data
to display the contact list.
goToContactDetail()
Function:
Redirects to the contact detail page when a contact is selected. It retrieves the contact’s id
from data-id
and navigates to /pages/contactDetail/contactDetail?id=${id}
, or shows an error if no id
is found.
contactDetail.wxml
Container (<view class="container">
): The outer wrapper for the contact details page layout, defining spacing and alignment.
Header (<view class="header">
): Displays the page title "联系人详情" at the top.
Avatar Section (<view class="avatar-section">
): Displays the contact's avatar. The src="{{contact.avatarUrl || '/images/default-avatar.png'}}"
attribute checks if avatarUrl
exists; if not, it defaults to /images/default-avatar.png
. The mode="aspectFill"
scales the image proportionally to fill the space.
Contact Info Section (<view class="input-section">
): Contains fields like last name, first name, company, phone, and email, each with:
Label (<text class="label">
): Shows the field’s name, e.g., "姓氏" or "电话".Info (<text class="info">
): Displays the actual data for each field using the contact
object’s properties (e.g., contact.lastName
).
Delete Button (<button class="delete-btn" bindtap="deleteContact">
): A button at the bottom labeled "一键删除". The bindtap="deleteContact"
event calls the deleteContact
function when clicked, enabling deletion of the contact.
This setup provides a structured contact details view with options to display, scale, and delete contact data.
contactDetail.js
Initialize Cloud Database:
const db = wx.cloud.database();
sets up a connection to the cloud database, allowing read/write operations on the contacts
collection.
Data Object:
data: { contact: {} }
initializes an empty contact
object that will store contact details from the database.
onLoad
Function:
Runs when the page loads. It extracts the contact id
from options
and calls getContactDetail
to retrieve contact details, displaying an error if no id
is found.
getContactDetail
Function:
Fetches a specific contact’s details using their id
. If successful, it stores this data in contact
; otherwise, it displays an error.
Avatar Change Function:
changeAvatar
: Allows users to select a new avatar image using wx.chooseImage
, then updates avatarUrl
in the database and local data to reflect the change.
Input Handling Functions:
onLastNameInput
, onFirstNameInput
, onCompanyInput
, onPhoneInput
, onEmailInput
capture user inputs for various fields and store the values in the contact
object. This makes the data ready for saving or updating.
Saving Changes:
saveChanges
: Saves modified contact data to the database. It updates fields in contact
and displays a success message upon completion.
Deleting Contact:
deleteContact
: Shows a confirmation prompt and deletes the contact from the database if confirmed, displaying a success or failure message accordingly.
Creating this WeChat Mini Program has been a valuable learning experience, teaching me both the practical and conceptual aspects of front-end and back-end development. I gained hands-on experience with key tools and techniques, such as cloud database management, real-time data binding, and handling user interactions. Working through each stage of the app—structuring UI, implementing data handling, and integrating cloud functions—deepened my understanding of building responsive, user-friendly applications and sharpened my problem-solving skills when addressing challenges in functionality and design.