微信小程序組件傳參感覺和vue還是挺像的
父組件向子組件傳參
在小程序中父組件子組件傳參,主要使用properties屬性。演示下:
創建組件文件夾component,創建組件demoComponent,記得創建的時候選擇組件,不是page頁面
?組件代碼,這里簡單寫了一個tab欄,動態判斷綁定類名
<view class="tablist">
<view class="tabitem {{item.id==active ?'active' :''}}" wx:for="{{tablist}}"> {{item.name}}</view>
</view>
在?properties里面生命一個active,來實現當前選中項,值為number類型
// component/demoComponent/demoComponent.js
Component({/*** 組件的屬性列表*/properties: {active:{type:Number}},/*** 組件的初始數據*/data: {tablist:[{id:1,name:'全部'},{id:2,name:'零食'},{id:3,name:'飲料'},],},/*** 組件的方法列表*/methods: {}
})
?
.tablist{display: grid;grid-template-columns: repeat(3,1fr);
}
.tabitem{text-align: center;padding: 10px 0;
}
.active{border-bottom: 3px solid blue;
}
在頁面中使用的時候,需要在json中聲明
{"usingComponents": {"demoComponent":"/component/demoComponent/demoComponent"}
}
這里傳入active為2?
<demoComponent active='2' />
當組件渲染的時候,第二項被賦上active樣式
子向父傳參?
使用自定義事件,triggerEvent。這點和vue非常相似,傳入兩個參數,第一個參數為自定義事件名,第二個為傳遞的值。演示下,稍微修改下組件代碼
綁定事件
<view class="tablist">
<view bind:tap="sendInfo" class="tabitem {{item.id==active ?'active' :''}}" wx:for="{{tablist}}"> {{item.name}}</view>
</view>
?使用triggerEvent來傳遞數據(組件js代碼,寫在methods中)
sendInfo(){const data={name:'zs',age:12}this.triggerEvent('sendData',data)}
父組件接受
<demoComponent active='2' bind:sendData="getData"/>getData(e){console.log('e',e.detail);},
當點擊組件的時候,可以從控制臺看到拿到從子組件傳遞的值了
跨組件傳參?
建議使用全局變量,在微信小程序中,全局變量寫在app.js中globalData對象里面,在頁面中通過getApp() 方法即可訪問到app.js里面的方法和全局變量。全局方法不需要寫在methods里面,和globalData同一級的
globalData: {myInfo:{name:'aaaaa',age:1231212}},getMethosFunc(){console.log('獲取app.js的方法');}
onLoad(options) {const app=getApp();console.log('myinfo',app.globalData.myInfo);app.getMethosFunc();},
end?