手记

this.triggerEvent()用法

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

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


    image.png

  • 组件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)
    }

image.png



作者:給我小鱼干
链接:https://www.jianshu.com/p/8b1c8609bbab


0人推荐
随时随地看视频
慕课网APP