最近嘗試學習微信小程序:
微信小程序中重要開發環節,組件.在這里說的是自定義組件;(其實也就是跟普通組件沒有什么區別),
1.先定義一個組件;假設在 /ponent/liu (分別有4個文件,跟page頁面一樣 liu.js | liu.json | liu.wxml | liu.wxss);
liu.wxml 如下:
<text>我是組件中的數據</text> <view class='hahaha'> <slot /> </view>
liu.js如下:
// ponent/liu/liu.js var beha01 = require("../behavior/beha01"); Component({ /** * 組件的屬性列表 */ behaviors: [beha01], //behaviors引入了一個behavior先不管; properties: { ajaxdata:{ type:"String", value:"", observer:function(new_val,old_val,path){ console.log("值變化了...") } }, liu_value: { type:"String", value: "lhf", observer:function(news,olds){ console.log(news,olds) this.setData({ }) } }, flow:{ type:"String", value:"", observer:function(news,olds,path){ console.log(news,olds) } } }, /** * 組件的初始數據 */ data: { ctext:"試試把我的值傳到page頁面" }, /** * 組件的方法列表 */ methods: { }, ready:function(){ console.log("liuliu組件中的數據:" ,this.data) } })
liu.json { "component": true",usingComponents": { } }
2.先說數據怎么從page流向Componnets;
page中的index.json如下: 標綠色的為引入配置
{ "navigationBarBackgroundColor":"#ccc", "navigationBarTextStyle":"black", "navigationBarTitleText":"微信小程序首頁(引入自定義彈窗組件)", "backgroundColor":"#000000", "backgroundTextStyle":"dark", "enablePullDownRefresh":true, "usingComponents":{ "my-toast":"/ponent/toast/toast", "liuhf":"/ponent/liu/liu" } }
page中的index.wxml如下:
<view>下面是普通組件</view> <liuhf flow="{{flowtochild}}" bind:myevent="onMyevent" > <text>我是一段文字,我將被放入這個組件的slot中</text> </liuhf>
<view>{{ctext}}</view>
page中的index.js如下:
Page({ data: { motto: '組件的開發', text:"點擊我可以更給我的內容啊", flowtochild:"我是page的數據,我的數據直接流向組件",
ctext:"我的內容可以通過組件觸發改變"
}, onReady:function(){ },
//定義的事件:
onMyevent:function(e){
var get_text=e.detail.ctext;
this.setData(
{"ctext":get_text}
)
}
})
開始了,使用組件:(在index.wxml中使用);這樣的;
<liuhf flow="{{flowtochild}}"> <text>我是一段文字,我將被放入這個組件的slot中</text> </liuhf>
flow的值,來自page頁面;而flow這個 屬性(porperty) 將對應到 liu.js(組件) properties 下的 flow;
當組件掛載完成:
ready:function(){
console.log("liuliu組件中的數據:" ,this.data); //其實this.data===this.properties ==>true;
};
//結果:
3.Componnets數據流向page (通過綁定事件和觸發事件傳遞數據) (當然最簡單的一種表現就是直接在組件中塞入數據,這里其實是說的事件觸發)
(示例:比如我們要改變 page中index.wxml中的 ctext這個顯示的數據)
3.1 在組件的使用的地方(index.wxml)綁定事件函數 bind:myevent="onMyevent"
並在index.js 中寫出具體方法: onMyevent:function(e){console.log(e)}
3.2 在組件中觸發事件(liu.js): 在methods寫:
methods: {
onTap:function(){
var myEventDetail = { // detail對象,提供給事件監聽函數 //監聽函數可以通過e.detail查看傳遞的數據;
hidden: false,
text: this.data.ctext
}
var myEventOption = {
} // 觸發事件的選項
this.triggerEvent('myevent', myEventDetail, myEventOption);
}
}
ok:完成數據傳遞.