小程序中巍膘,我們有時(shí)候需要自己定義一些組件,方便我們使用芋簿,下面就講解一下小程序中component的使用峡懈,以及互相調(diào)用方法及傳遞參數(shù)。
我們舉個(gè)例子:在index頁(yè)面定義一個(gè)叫my-button的組件与斤。下面就動(dòng)手起來(lái)吧肪康。
1.創(chuàng)建component荚恶,取名為my-button,在index.json文件夾下面引入自定義的組件
2.在my-button組件中自定義我們的屬性磷支。
在這里我們就定義一個(gè)屬性谒撼,button的文字
//在properties里面定義我們要的屬性
properties: {
btText: {//btText表示我們屬性的名字
value: '默認(rèn)值',//value表示默認(rèn)值
type: String //type是我們定義的類型,這里是String字符串類型
}
},
3.在index頁(yè)面中調(diào)用我們的自定義的my-button組件雾狈。
<view class="container">
<my-button btText='自定義按鈕'/>//my-button就是我們自定義組件的名字-----btText就是我們屬性的名字
</view>
4.在index中調(diào)用my-button里面的方法廓潜。
首先我們?cè)谧远x的my-button里面定義一個(gè) 方法,如下定義一個(gè)showLog方法:
Component({
/**
* 組件的屬性列表
*/
properties: {
btText: {
value: '默認(rèn)值',
type: String
}
},
/**
* 組件的初始數(shù)據(jù)
*/
data: {
},
/**
* 組件的方法列表
*/
methods: {
//my-button的方法
showLog:function(){
console.log("我是自定義button的log")
}
}
})
然后在index里面我們加一個(gè)按鈕善榛,點(diǎn)擊一個(gè)按鈕去調(diào)用my-button里面的方法辩蛋,并且我們要給自定義的button加一個(gè)id
<!--index.wxml-->
<view class="container">
<button bindtap='hahaTap'>哈哈</button>//加了一個(gè)按鈕點(diǎn)擊后去調(diào)用自定義按鈕里面的方法
<my-button id='myBtn' btText='自定義按鈕' /> //加一個(gè)id
</view>
我們?cè)趇ndex.js里面獲取我們的自定義的button
const app = getApp()
Page({
data: {
},
onLoad: function() {
//通過(guò)id獲取組件component
this.myButton = this.selectComponent("#myBtn")
},
/**
* 按鈕點(diǎn)擊事件,去調(diào)用自定義組件里面的方法
*/
hahaTap: function() {
//showLog是自定義組件我們定義的方法名
this.myButton.showLog();
}
})
然后我們就可以看見(jiàn)showLog()方法被調(diào)用后的log輸出了
5.在my-button中調(diào)用index里面的方法。
我們?cè)趇ndex.js里面建一個(gè)方法
indexFunction:function(){
}
在my-button里面給按鈕加一個(gè)點(diǎn)擊事件移盆,點(diǎn)擊后調(diào)用index里面的indexFunction方法
methods: {
//my-button的方法
showLog:function(){
console.log("我是自定義button的log")
},
/**
* 自定義按鈕的點(diǎn)擊事件
*/
clickTap:function(){
}
}
我們給自定義按鈕加了個(gè)點(diǎn)擊事件clickTap方法悼院,點(diǎn)擊后觸發(fā)這個(gè)方法去掉用index里面的indexFunction();
下面需要我們?cè)趇ndex布局的自定義控件button去加一下我們的bind方法
然后我們?cè)谧远x按鈕點(diǎn)擊方法中去調(diào)用index里面的方法
my-button.js里面的method
/**
* 組件的方法列表
*/
methods: {
//my-button的方法
showLog:function(){
console.log("我是自定義button的log")
},
/**
* 自定義按鈕的點(diǎn)擊事件
*/
clickTap:function(){
this.triggerEvent('indexFunction')
}
}
index.js
const app = getApp()
Page({
data: {
},
onLoad: function() {
//通過(guò)id獲取組件component
this.myButton = this.selectComponent("#myBtn")
},
/**
* 按鈕點(diǎn)擊事件,去調(diào)用自定義組件里面的方法
*/
hahaTap: function() {
//showLog是自定義組件我們定義的方法名
this.myButton.showLog();
},
indexFunction:function(){
console.log("index里面的方法被調(diào)用了")
}
})