一、小程序概述
微信小程序是一種新型的輕應用,無需安裝即可使用,可以在微信聊天會話界面中直接進入。小程序具有輕量、快捷、省流量、不佔內存等特點,成為了越來越多企業和個人的開發選擇。
小程序開發擁有較高的技術門檻,但只要不斷學習,積累,就可以逐漸提高技術水平。在本文中,我們將會介紹一些基礎概念和基本操作,以及一些實用技巧,幫助初學者快速入門。
二、小程序開發環境配置
在開始小程序開發之前,我們需要先進行開發環境的配置。
1、下載並安裝小程序開發者工具。
2、創建小程序項目。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>頁面標題</title>
</head>
<body>
<div>
<p>頁面內容</p>
</div>
</body>
</html>
3、安裝並引入微信小程序官方UI庫 WXML。
<template name="footer">
<view class="container">
<view class="footer">
<view class="ucenter">
<navigator hover-class="none" url="/pages/mine/mine">
<image src="/images/icon/user.png" />
<text>個人中心</text>
</navigator>
</view>
<navigator hover-class="none" url="/pages/index/index" class="ft-nav">
<image src="/images/icon/home.png" />
<text>首頁</text>
</navigator>
</view>
</view>
</template>
三、小程序基本概念
1、WXML(WeiXin Markup Language)是微信小程序頁面結構語言,類似於HTML。
<view>
<view class="item">
<image src="../../images/icon/user.png" class="item-img"/>
<text class="item-txt">個人中心</text>
</view>
</view>
2、WXSS( WeiXin Style Sheets)是微信小程序頁面樣式表描述語言,類似於CSS。
.item-img{
width: 50px;
height: 50px;
margin: 0 10px 0 20px;
}
.item-txt{
color: #333;
font-size: 16px;
}
3、JavaScript 語言。
Page({
data: {
message: 'Hello World!'
},
onLoad: function () {
console.log('onLoad')
}
})
四、小程序API的使用
1、頁面生命周期函數。
常用的生命周期函數有:
- onLoad:監聽頁面加載
- onShow:監聽頁面顯示
- onReady:監聽頁面初次渲染完成
- onHide:監聽頁面隱藏
- onUnload:監聽頁面卸載
Page({
onLoad: function () {
console.log('onLoad')
},
onShow: function () {
console.log('onShow')
}
})
2、註冊小程序組件。
//註冊一個名為 test 的組件
Component({
properties: {
text:{
type: String,
value: "default value"
}
},
methods: {
onTap: function() {
console.log("text:", this.properties.text);
}
}
})
3、自定義組件的使用。
<test text="this is test."></test>
五、小程序實用技巧
1、在代碼中使用事件委託。
<view bindtap="handleTap">
<view class="item">
<image src="../../images/icon/user.png" class="item-img"/>
<text class="item-txt">個人中心</text>
</view>
<view class="item">
<image src="../../images/icon/cart.png" class="item-img"/>
<text class="item-txt">購物車</text>
</view>
</view>
handleTap: function(e){
var target = e.target,
id = target.dataset.id;
console.log(id);
}
2、使用 ES6 的 Promise 解決回調地獄問題。
new Promise(function(resolve, reject){
wx.request({
url: 'http://localhost:8080/posts/1',
success: function(res){
resolve(res.data);
},
fail: function(){
reject();
}
})
}).then(function(data){
console.log(data);
}).catch(function(){
console.log('fail');
});
3、封裝 request。
function request(url, data={}, method='GET'){
return new Promise(function(resolve, reject){
wx.request({
url,
data,
method,
success: function(res){
resolve(res);
},
fail: function(error){
reject(error);
}
})
})
}
request('https://jsonplaceholder.typicode.com/posts/1')
.then(function(res){
console.log(res.data);
})
.catch(function(error){
console.log(error);
})
六、結語
以上就是微信小程序開發的一些基礎概念和 API 的簡單介紹,小程序是一個非常有潛力的發展平台,學會基礎開發技術後,可以根據自己的需求和興趣獨立完成開發。希望本文對初學者有所幫助!
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/195439.html
微信掃一掃
支付寶掃一掃