小程式學習之旅----自定義元件toast例項
阿新 • • 發佈:2018-11-02
components目錄下新建資料夾toast,新建component,之後修改toast.js和toast.wxml
<!--components/toast/toast.wxml-->
<view class='wx_toast_container' hidden="{{!toastShow}}">
<view class='wx_toast_text'>{{toastText}}</view>
</view>
// components/toast/toast.js Component({ /** * 元件的屬性列表 */ properties: { }, /** * 元件的初始資料 */ data: { toastShow: false, toastText: '內容' }, /** * 元件的方法列表 */ methods: { showToast (text, time) { this.setData({ toastShow: !this.data.toastShow, toastText: text }) var that = this if (!time) { time = 8000 } setTimeout(function () { that.setData({ toastShow: !that.data.toastShow }) }, time) } } })
元件建好之後,在news父元件裡引用
{
"navigationBarTitleText": "新聞頁面",
"usingComponents": {
"br": "../../components/br/br",
"header": "../../components/header/header",
"cart": "../../components/cart/cart",
"toast": "../../components/toast/toast"
}
}
父元件主動呼叫子元件方法
<!--pages/news/news.wxml--> <header title='{{title}}'></header> <view> 新聞 </view> <text>你好</text> <br /> <text>元件</text> <toast id='toast'></toast> <br /> <button type='primary' bindtap='showToast'>顯示toast自定義元件</button>
// pages/news/news.js Page({ /** * 頁面的初始資料 */ data: { title: '新聞元件title' }, showToast () { console.log(this.toast) this.toast.showToast('我是toast元件傳過來的值', 2000) }, /** * 生命週期函式--監聽頁面載入 */ onLoad: function (options) { this.toast = this.selectComponent('#toast') } })
這樣,自定義元件就ok了