關於微信小程序中組件和頁面方法的互相調用

 

一、通過組件調用頁面裏面的方法:

我們這裏用header組件和user頁面來舉例:


    1.先在header組件js頁面的methods中,寫一個方法,然後用triggerEvent給監聽的事件起一個名字,這裏叫做run
    2.在header.wxml中,使用bindtap綁定這個getUserFn方法,一般會綁定到按鈕上
    3.在user.wxml中,調用header組件,並且bind:run="user組件中的方法名"

 

組件邏輯header.js

methods: {
    
    getUserFn(){
      const myEventDetail = {} // detail對象,提供給事件監聽函數

      this.triggerEvent("run", myEventDetail)
      //第一個參數,就是給這個事件起個名字,要在組件的bind後面用,第二個參數是傳入數據,還有第三個參數冒泡啥的
    }

組件頁面header.wxml:

<button bindtap='getUserFn'>通過組件使用USERS裏面的方法</button>

用戶頁面user.wxml:bind後面的run就是我們在triggerEvent中,給事件起的名字,後面的test,就是我們要調用的user.js中的方法

<header  bind:run="test"></header>

用戶邏輯user.js:

test(){
    console.log("我是user.js中的test方法")
}

二、通過頁面,調用組件中的方法:


  通過user頁面,調用header組件:
  1.在user頁面中使用header組件,給他起一個ID
  2.在user.js中,獲取到這個組件(實例化)
  3.通過實例化的對象,即可調用組件中的方法
 

用戶頁面user.wxml

<header id="header"><header> //在頁面中調用組件,然後給他起個ID
<button bindtap="useComponentFn">通過頁面調用組件中的方法</button>

用戶邏輯user.js


  onLoad: function(options) {
    this.header = this.selectComponent("#header"); //這裏是實例化了header,通過header,我們就能調用header組建中的方法
  },
  useComponentFn(){
    this.header.componentFn();//調用了組建中的componentFn方法  
  }

組件邏輯header.js中的method中

componentFn(){
    console.log("我是header中的方法")
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章