微信小程序 this.triggerEvent()的具体使用

来自:互联网
时间:2020-05-27
阅读:

在对组件进行封装时 在当前页面想要获取组件中的某一状态,需要使用到this.triggerEvent(' ',{},{}),第一个参数是自定义事件名称,这个名称是在页面调用组件时bind的名称,第二个对象就可以将想要的属性拿到,第三个参数文档中有介绍,有机会再做补充。

在这个demo中like组件是我要封装的组件,在classic.wxml中调用的:

微信小程序 this.triggerEvent()的具体使用

组件like.vue的页面是这样写的:

<view bind:tap="onLike" class="container">
 <image src="{{like?yesSrc:noSrc}}" />
 <text>{{count}}</text>
</view>

组件的like.js中methods是这样写的:

methods: {
    onLike(event) {
      let like = this.properties.like;
      let count = this.properties.count;
      count = like ? count - 1 : count + 1;
      this.setData({
        like: !like,
        count
      })
      let behavior = this.properties.like ? "like" : "cancel";
      this.triggerEvent('like', {
        behavior
      }, {})
    }
  }

那么在classic.wxml中调用组件:

这里要注意bind:后面的like是this.triggerEvent()的第一个参数,自定义事件名称

<v-like bind:like="onLike" like="{{classicData.like_status}}" count="{{classicData.fav_nums}}"/>

classic.js中onlike就可以实现页面对组件属性的获取:

 onLike: function(event) {
    console.log(event)
  }

微信小程序 this.triggerEvent()的具体使用

event.detail.behavior就可以拿到是不是喜欢的属性了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

返回顶部
顶部