1. 程式人生 > 程式設計 >小程式的基本使用知識點(非常全面,推薦!)

小程式的基本使用知識點(非常全面,推薦!)

目錄

    註冊App時做什麼呢?

    1. 判斷小程式的進入場景
    2. 監聽生命週期函式,在生命週期中執行對應的業務邏輯,比如在某個生命週期函式中獲取微信使用者的資訊。
    3. 因為App()例項是全域性共享的(單例物件),所以我們可以將一些共享資料放在這裡。

    註冊page頁面時,我們一般需要做什麼呢?

    1. 在生命週期中傳送網路請求,從伺服器獲取資料;
    2. 初始化一些資料,以方便被wxml引用展示
    3. 監聽wxml中的一些事件,繫結對應的事件函式
    4. 其他一些監聽,(比如頁面滾動,上拉重新整理,下拉載入更多等)

    關於wxml的template和include

    在wxml中是不能直接呼叫Page/Component中定義函式的

    在wxml檔案中定義template標籤,template標籤在沒有呼叫的情況下是不會進行任何渲染

    name屬性和is屬性對應;可以使用{{}}語法

    <template name="compoent">
    <view>哈哈哈</view>
      <text>嘿嘿嘿</text>
      <text>{{name}}</text>
      <text>{{age}}</text>
    </template>
    <template is="compoent"/>
    <template is="compoent"/>
    <template is="compoent"/>
    <template is="compoent" data= "{{name: '小屏',age:'123'}}" />
    

    關於wxml的匯入有兩種方式:

    impowww.cppcns.comrt匯入:

    1:主要是匯入template

    2:特點是 不能進行遞迴匯入

    include引入:

    1:將公共的元件抽取到一個檔案中

    特點:不能匯入template/wxs/可以進行遞迴匯入

    wxs模組

    wxs模組是小程式的一套指令碼語言結合wxml,可以構建出頁面的結構

    wxs與javascript是不同的語言,有自己的語法,並不和javaScript一致。(不過基本一致)

    在wxml中是不能直接呼叫Page/Component中定義函式的

    但是某些情況下,我們希望使用函式來處理wxml中的資料(類似vue在的過濾器),這個時候就使用wxs了

    wxl使用的限制和特點:

    WXS的執行環境和其他的JavaScript程式碼是隔離的,wxs中不能呼叫其他Javascript檔案中定義的函式,也不能呼叫小程式中的API

    wxs不能作為陣列的函式回撥。

    由於執行環境的差異,在ios裝置上的小程式內的wxs會比JavaScript快2~20.倍,在android裝置上二者執行效率無差異。

    小程式元件化相關

    小程式元件和呼叫該元件的頁面樣式互不影響。

    呼叫元件需要在頁面的json檔案中加入元件名稱和路徑

    {
      "usingComponents": {
        "my-cut":"/pages/compent/my-cut"  }
    }
    

    在有需要是頁面和元件間的樣式相互影響的時候,可以利用options的 styleIsolation屬性

    在元件的js檔案Component({})下面

      // 在元件裡面設定options的 styleIsolation: "apply-shared"會是頁面設定的樣式屬性影響元件的樣式
      // 在元件裡面設定options的 styleIsolation: "shared"會是頁面設定的樣式屬性影響元件的樣式
      Component({
    	options:{
        styleIsolation: "apply-shared"
      },})
    
    

    元件間的動態轉值使用properties屬性

    在元件中可以利用externalClasses這個屬性來動態設定設定css的樣式

    Component({
    properties: {
        // title: String
        title:{
          type: String,value:"我是預設值",//監聽新值和舊值
          observer: function(newVal,oldVal){
            console.log(newVal,oldVal)
          }
        },},// 在元件中可以利用這個屬性來動態設定設定css的樣式
      externalClasses:["tltleclass"]
    
    })
    
    

    在頁面中呼叫屬性

    <my-cut title="哈哈" tltleclass="red"></my-cut>
    <my-cut title="嘿嘿" tltleclass="green" />
    <my-cut/>
    

    頁面css檔案

    .red{
      color: red;
    }
    .green{
      color: green;
    }
    

    元件到頁面間的函式呼叫

    在頁面使用元件的時候,我們有時候會需要修改元件的資料,這就需要我們在頁面的js檔案呼叫到元件的data。

    在小程式中有個selectComponent('.class/#xxx')可以拿到元件物件;

    元件wxml

    <view class="contention">
      <block wx:for="{{titled}}" wx:key="index">
        <view class="tit"> <text class="intext {{index == increat? 'active' : ''}}" data-count="{{index}}" bindtap="targetTap">{{item}}</text> </view>
      </block>
    </view>
    

    元件js

    methods: {
        targetTap(e){
          const index  = e.currentTarget.dataset.count
          this.setData({
            increat:index
          })
            this.triggerEvent("targetCount",{})
        },amend(){
          this.setData({
            titled: ["政治","數學","英語"]
          })
        }
    
      }
    

    頁面wxml

    <switch titled="{{list}}" bind:targetCount="targetCount" class="sw-class"></switch>
    

    頁面js

      targetCount(){
      //獲取元件物件
        const content = this.selectComponent('.sw-class') 
        console.log(content)
        // content.setData({
        //   titled:["政治","英語"]
        // })
        // 開放規範一般不推薦這種直接在函式的修改方法,建議在元件內使用methods內部以方法的形式修改,在頁面呼叫即可
        content.amend()
      },

    小程式元件插槽的使用

    單插槽

    元件wxml

    <view>
      我是一個標題
    </view>
    <slot></slot>
    <view>
      我是一個內容
    </view>
    

    頁面wxml使用

    <my-slot>
    <button size="mini"> 按鈕</button>
    </my-slot>
    <my-slot>
     <image src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg2.woyaogexing.com%2F2021%2F04%2F26%2F1b402c98095d452486508b8250b21f3f%21360x640.jpeg&refer=http%3A%2F%2Fimg2.woyaogexing.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625711145&t=d9d310d5e9c878a9d4b7bc7057f2b754"/>
    </my-slot>
    <my-slot>
      <slider value="20"></slider>
    </my-slot>
    

    多個插槽的使用

    需要給每一個插槽取一個名字使用name屬性

    必須在component物件下面的options物件下面的multipleSolts屬性設定為true

    元件wxml

    <view>我是多插槽的標題</view>
    <view> <slot name="slot1" ></slot> </view>
    <view> <slot name="slot2" ></slot> </view>
    <view> <slot name="slot3" ></slot> </view>
    <view>我是多插槽的尾部</view>
    

    元件js檔案

    Component({
      /**
       * 元件的屬性列表
       */
      options:{
        multipleSlots:true
      }
      )}
    

    頁面的使用

    <!-- 多插槽的使用 -->
    <!-- 注意事項:
    需要給每一個插槽取一個名字
    必須在component物件下面的options物件下面的multipleSolts屬性設定為true -->
    <my-mslot>
    <button slot="slot3">415461</button>
    <slider slot="slot1" value="20"></slider>
    <text slot="slot2">呵呵呵呵呵</text>
    </my-mslot>
    

    小程式元件的Component構造器有那些作用

    1 properties 讓使用者可以給元件傳入資料

    properties:{ 
    	title: string,content:{
    	type: array,value:[1,2.3],observer:function(newVal,oldVal)
          }
    	}
    }
    

    2.data 定義一些元件的初始化資料

    data:{
    	counter:0
    }	
    

    3 methods 用於定義元件內部的函式

    methods:{
    foo(){
    	
    }
    }
    

    4 options 定義元件的配置選項

    options:{
    //在需要使用多插槽時設定為true
    	multipleSlots:true,//設定樣式的隔離方式
    	styleIsolation: "apply-shared",//頁面設定的樣式屬性影響元件的樣式
       //styleIsolation: "shared"  頁面設定的樣式屬性影響元件的樣式
    }
    

    5 externalClasses 定義外部傳入額外的樣式

    externalClasses:["on","tre"]
    

    6 observers可以監聽properties/data的改變

    observers:{
    	counter: function(newVal){
    		console.log(newVal)
    	}
    }
    

    7 監聽所在頁面的生命週期

    在元件js檔案

      pageLifetimes:{
        show(){
          console.log("監聽元件所在頁面顯示出來的")
        },hide(){
          console.log("監聽元件所在頁面隱藏起來的時候")
        },resize(){
          console.log("監聽頁面尺寸的改變")
        }
      }
    

    監聽元件內生命週期

    lifetimes:{
        created(){
          console.log("元件被建立")
        },attached(){
          console.log("元件被新增到頁面中")
        },ready(){
          console.log("元件被渲染出來")
        },moved(){
          console.log("元件被移動到節點樹的另一個位置")
        },detached(){
          console.log("元件")
        }
      }
    

    小程式網路請求

    onReady: function () {
        wx.request({
          url: 'http://httpbin.org/post',method:'post',data:{
            name:"wangshuai",age:19
          },success:function(res){
              console.log(res)
          }
        })
      },

    小程式的基本使用知識點(非常全面,推薦!)

    比較關鍵的幾個屬性

    1. url: 必傳
    2. data:MCJdkSM 請求引數
    3. method:請求的方式
    4. success:成功時的回撥
    5. fail:失敗時的回撥

    一般情況下為了降低網路請求和wx.request的耦合度,我們會Promise的方法獲取回撥結果

    使用promise封裝

    export default function request(option) {
        return new Promise( (resolve,reject) => {
          wx.request({
            url: option.url,method: option.method || 'get',data: option.data || {},MCJdkSM   success: function (res) {
                resolve(r程式設計客棧es)
            },fail: function (res) {
              reject(res)
            }
          })
        })
    }
    

    頁面呼叫

     onReady: functi程式設計客棧on () {
        //小程式原生網路請求
        // wx.request({
        //   url: 'http://httpbin.org/post',//   method:'post',//   data:{
        //     name:"wangshuai",//     age:19
        //   },//   success:function(res){
        //       console.log(res)
        //   }
        // })
        request({url: 'http://httpbin.org/post',method:"post"}).then(res=>{
          console.log(res)
        }).catch(err =>{
          console.log(err)
        })
      },

    小程式中的彈窗展示

    頁面wxml

    <button size="mini" bindtap="showToast">showToast</button>
    <button size="mini" bindtap="showModal">showModal</button>
    <button size="mini" bindtap="showLoading">showLoading</button>
    <button size="mini" bindtap="showAction">showAction</button>
    <button size="mini" open-type="share">分享</button>
    

    頁面js檔案

    Page({
    	showToast(){
        wx.showToast({
          title: '我是showToast',})
      },showModal(){
        wx.showModal({
          title:'是否刪除',cancelColor: 'cancelColor',success:function (params) {
              console.log(params)
              if (params.cancel) {
                  console.log("點選了取消刪除")
              } 
          } 
        })
      },showLoading(){
        wx.showLoading({
          title: '等待中',mask: true //給一個遮罩,防止其他操作
        })
        setTimeout(()=>{
          wx.hideLoading({
            success: (res) => {},})
        },1500)
      },showAction(){
        wx.showActionSheet({
          itemList: ['拍照','檔案'],})
      }
    })
    

    小程式頁面分享

    小程式的分享方式有兩種,一種是點選按鈕分享,另一種是點選右上角的選單選項選擇分享。

    我們分享小程式的時候需要通過onShareAppMessage來展示分享資訊

    監聽使用者點選頁面內轉發按鈕(button 元件 open-type=“share”)或右上角選單“轉發”按鈕的行為,並自定義轉發內容。

    小程式的基本使用知識點(非常全面,推薦!)

    注意:只有定義了此事件處理函式,右上角選單才會顯示“轉發”按鈕
    此事件處理函式需要 return 一個 Object,用於自定義轉發內容,返回內容如下:

    小程式的基本使用知識點(非常全面,推薦!)

    關於小程式的跳轉

    navigator標籤

    關於navigator跳轉使用url.

    <navigator url="/pages/home/home">跳轉home</navigator>
    

    跳轉屬性open-type有如下取值

    redirect:關閉當前頁面,跳轉到應用內的某個頁面。但是不允許跳轉到tabBer頁面,並且不能返回

    switchTab:跳轉到tabBer頁面,並關閉其他非tabber頁面(需要在tabBer中定義)

    reLaunch:關閉所有頁面,開啟某個頁面(直接展示某個頁面,斌切可以跳轉到tabBer頁面)

    <navigator url="/pages/home/home">跳轉home</navigator>
    <navigator url="/pages/home/home" open-type="redirect">跳轉home(redirect)</navigator>
    <navigator url="/pages/home/home" open-type="reLaunch">跳轉home(reLaunch)</navigator>
    <navigator url="/pages/home/home" open-type="switchTab">跳轉home(switchTab)</navigator>
    

    總結

    到此這篇關於小程式的基本使用的文章就介紹到這了,更多相關小程式基本使用內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!