小程序学习之旅----自定义组件toast实例

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了

猜你喜欢

转载自blog.csdn.net/qfxlw/article/details/83384089