怎么在Page的wxml上对自定义组件的方法进行路由?
发布于 4 年前 作者 yanjun 1934 次浏览 来自 官方Issues

比如我实现一个新增用户地址的按钮,但新增用户地址只是这个按钮组件的方法之一,我想在组件的wxml标签上直接填这个组件内部新增用户地址的方法,不想再扯到页面逻辑层里,能实现吗?

下面是一个设想例子,让组件接受来自page的函数名以决定调用哪个方法,要是eval没被禁我也就不用问这题了.

xxpage.wxml

 <img-btn-comp bindCompMethod="addressInfo" >
      <view class='redirect-address' slot="address">
        <text class='redirect-text'>新增收货地址</text>
        <icon class='iconfont icon-webicon213'></icon>
      </view>
    </img-btn-comp>

component/img-button

// components/image-button/index.js

Component({
  /**
   * 组件的属性列表
   */
  options: {
    multipleSlots: true
  },
  properties: {
    openType: {
      typeString
    },
    imageSrc: {
      typeString
    },
    bindCompMethod: {
      typeString
    },
    bindGetUserProfile: {
      typeString
    }

  },

  /**
   * 组件的初始数据
   */
  data: {
    addressInfo: ""
  },

  /**
   * 组件的方法列表
   */
  methods: {
    methodRoute() {
      console.log(this.data.bindCompMethod);
    },
    onGetUserProfile(event) {
      console.log(this.data);
      console.log(event.detail);
      if (this.data.openType == "getuserprofile") {
        this.triggerEvent('getUserProfile', event.detail, {})
      }
    },
    address(event) {
      console.log(event.detail);
      if (this.data.openType == "primary") {
        this.addressInfo(event);
      }
    },
    addressInfo(e) {
      wx.chooseAddress({
        success: res => {
          console.log(res);
          this.setData({
            addressInfo: res
          })
        },
        fail: (err) => {},
        complete: e => {
          if (e.errMsg == "chooseAddress:ok") {
            this.triggerEvent('addressInfo', {
              addressInfo: this.data.addressInfo,
              status: "ok"
            }, {})
          } else {
            this.triggerEvent('addressInfo', {
              status: "error"
            }, {})
          }
        }
      })
    }
  }
})

回到顶部