>  기사  >  위챗 애플릿  >  맞춤형 WeChat 애플릿 구성요소(모달 팝업 구성요소)에 대한 자세한 설명

맞춤형 WeChat 애플릿 구성요소(모달 팝업 구성요소)에 대한 자세한 설명

php是最好的语言
php是最好的语言원래의
2018-08-01 10:05:238478검색

미니 프로그램은 언제부터 인기를 얻었는지 알 수 없습니다. 안드로이드든, iOS든, 인기 있는 위챗 미니 프로그램이든, 개발에 종사하는 분들은

공식 네이티브 컨트롤은 더 이상 개발 요구 사항을 완벽하게 충족할 수 없으므로 이 기사에서는 맞춤형 WeChat 애플릿 구성 요소(모달 팝업 구성 요소)를 소개합니다.

먼저 사진을 찍어 보겠습니다.

맞춤형 WeChat 애플릿 구성요소(모달 팝업 구성요소)에 대한 자세한 설명

이것을 보면 렌더링이 여전히 약간 매력적입니다. 하하, 더 이상 말도 안 되는 소리는 하지 말고 코딩을 시작하겠습니다. . .

총 4개의 파일이 있는데, js, json, xml, wxss 입니다. 아직도 헷갈리신다면 나갈 때 왼쪽으로 돌아서 5분 정도 생각해보세요.

먼저 대화 상자.xml 파일을 레이아웃하고

<!--mask dialog-->
<view class="drawer_screen" bindtap="hideDialog" wx:if="{{isShow}}" catchtouchmove="myCatchTouch"></view>
<!--content-->
<!--使用animation属性指定需要执行的动画-->
<view animation="{{animationData}}" class="drawer_box" wx:if="{{isShow}}">

  <!--drawer content-->
  <view class=&#39;row&#39;>
    <view class="drawer_title" style=&#39;width:100%;padding-left:60rpx&#39;>{{title}}</view>
    <icon type="clear" style=&#39;margin-top:40rpx;margin-right:20rpx;&#39; bindtap="hideDialog"></icon>
  </view>
  <form bindsubmit="_formSubmit">
    <scroll-view scroll-y>
      <view class="drawer_content">
        <view wx:for="{{dataObject}}" wx:key="{{id}}">
          <view class="top grid">
            <label class="title col-0" style="color:red" wx:if="{{item.must}}">*</label>
            <label class="title col-0" wx:else> </label>
            <input class="input_base input_h30 col-1" placeholder=&#39;{{item.placeholder}}&#39; wx:if="{{item.type === type_input}}" name="{{item.id}}" value="{{bean[item.id]}}"></input>
            <view class="input_base input_h30 col-1" wx:elif="{{item.id === id_sex}}" hover-class=&#39;btn_ok_hover&#39; bindtap=&#39;{{item.event}}&#39;>{{sexDefault}}</view>
            <view class="input_base input_h30 col-1" wx:elif="{{item.id === id_group}}" hover-class=&#39;btn_ok_hover&#39; bindtap=&#39;{{item.event}}&#39;>{{groupDefault}}</view>
          </view>
        </view>
      </view>
    </scroll-view>
    <button class="btn_ok" hover-class=&#39;btn_ok_hover&#39; formType="submit">确定</button>
  </form>
</view>

다음에 대화 상자.wxss 파일을

/*mask dialog start*/
.drawer_screen {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  right:0;
  bottom:0;
  z-index: 1000;
  background: #000;
  opacity: 0.5;
  overflow: hidden;
}

/*content*/

.drawer_box {
  width: 650rpx;
  overflow: hidden;
  position: fixed;
  top: 50%;
  left: 0;
  z-index: 1001;
  background: #fafafa;
  margin: -480rpx 50rpx 0 50rpx;
  border-radius: 6px;
}

.drawer_title {
  padding: 15px;
  font: 20px "microsoft yahei";
  text-align: center;
}

.drawer_content {
  height: 720rpx;
  /*overflow-y: scroll; 超出父盒子高度可滚动*/
}

.btn_ok {
  padding: 10px;
  font: 20px "microsoft yahei";
  text-align: center;
  border-top: 1rpx solid #e8e8ea;
  color: #3cc51f;
}

.btn_ok_hover {
  color: #aaa;
  background: #d9d9d9;
}

.top {
  padding-top: 8px;
}

.input_base {
  border: 2rpx solid #ccc;
  border-radius: 20rpx;
  padding-left: 20rpx;
  margin-right: 20rpx;
}

.input_h30 {
  height: 30px;
  line-height: 30px;
}

.title {
  height: 30px;
  line-height: 30px;
  width: 40rpx;
  text-align: center;
  display: inline-block;
  font: 300 28rpx/30px "microsoft yahei";
}

.grid {
  display: -webkit-box;
  display: box;
}

.col-0 {
  -webkit-box-flex: 0;
  box-flex: 0;
}

.col-1 {
  -webkit-box-flex: 1;
  box-flex: 1;
}

/*mask dialog end*/

.row {
  display: flex;
  flex-direction: row;
}

다음에 대화 상자.js 파일을

// components/Dialog/dialog.js
Component({
  options: {
    multipleSlots: true // 在组件定义时的选项中启用多slot支持
  },
  /**
   * 组件的属性列表
   */
  properties: {
    title: { // 属性名
      type: String, // 类型(必填),目前接受的类型包括:String, Number, Boolean, Object, Array, null(表示任意类型)
      value: &#39;标题&#39; // 属性初始值(可选),如果未指定则会根据类型选择一个
    }

  },

  /**
   * 组件的初始数据
   */
  data: {
    // 弹窗显示控制
    isShow: false,
    type_input: "input",
    type_btn: "button",
    id_sex: "sex",
    id_group: "group",
    dataObject: [],
    sexDefault: "男",
    groupDefault: "组织",
    sexArray: [&#39;男&#39;, &#39;女&#39;],
    groupArray: [&#39;组织&#39;, &#39;群众&#39;],
    bean: {},
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /*
     * 公有方法
     */
    setDataObj(dataObj,beanObj) {
      this.setData({
        dataObject: dataObj,
        bean: beanObj
      })
      if (beanObj.hasOwnProperty("sex") && beanObj.sex != ""){
        this.setData({
          sexDefault: beanObj.sex
        })
      }
      if (beanObj.hasOwnProperty("group") && beanObj.group != "") {
        this.setData({
          groupDefault: beanObj.group
        })
      }
    },
    //隐藏弹框
    hideDialog() {
      this._showOrCloseDialog("close")
    },
    //展示弹框
    showDialog() {
      this._showOrCloseDialog("open")
    },
    /*
     * 内部私有方法建议以下划线开头
     * triggerEvent 用于触发事件
     */

    _formSubmit(e) {
      if ("" === e.detail.value.name) {
        wx.showToast({
          title: &#39;请填写姓名&#39;,
          icon: &#39;none&#39;
        })
        return
      }
      if ("" === e.detail.value.phone) {
        wx.showToast({
          title: &#39;请填写电话&#39;,
          icon: &#39;none&#39;
        })
        return
      }
      this._showOrCloseDialog("close")
      //触发成功回调
      this.triggerEvent("confirmEvent", {
        e: e
      });
    },

    sexButton: function() {
      var that = this;
      wx.showActionSheet({
        itemList: this.data.sexArray,
        success: function(res) {
          console.log(res.tapIndex)
          that.setData({
            sexDefault: that.data.sexArray[res.tapIndex]
          })
        },
        fail: function(res) {
          console.log(res.errMsg)
        }
      })
    },
    groupButton: function() {
      var that = this;
      wx.showActionSheet({
        itemList: this.data.groupArray,
        success: function(res) {
          console.log(res.tapIndex)
          that.setData({
            groupDefault: that.data.groupArray[res.tapIndex]
          })
        },
        fail: function(res) {
          console.log(res.errMsg)
        }
      })
    },
    _showOrCloseDialog: function(currentStatu) {
      var that = this;
      /* 动画部分 */
      // 第1步:创建动画实例 
      var animation = wx.createAnimation({
        duration: 200, //动画时长
        timingFunction: "linear", //线性
        delay: 0 //0则不延迟
      });

      // 第2步:这个动画实例赋给当前的动画实例
      this.animation = animation;

      // 第3步:执行第一组动画
      animation.opacity(0).rotateX(-100).step();

      // 第4步:导出动画对象赋给数据对象储存
      that.setData({
        animationData: animation.export()
      })

      // 第5步:设置定时器到指定时候后,执行第二组动画
      setTimeout(function() {
        // 执行第二组动画
        animation.opacity(1).rotateX(0).step();
        // 给数据对象储存的第一组动画,更替为执行完第二组动画的动画对象
        that.setData({
          animationData: animation
        })

        //关闭
        if (currentStatu == "close") {
          that.setData({
            isShow: false
          });
        }
      }.bind(this), 200)

      // 显示
      if (currentStatu == "open") {
        that.setData({
          isShow: true
        });
      }
    }
  },
  //解决滚动穿透问题
  myCatchTouch: function () {
    return
  }
})

어떤 친구들은 이것을 보고 병렬 수입자이군요. js 파일 구조가 무엇인지 물어볼 수도 있습니다. ? 왜 우리와 다른가요? 걱정하지 마십시오. 제 말을 들어주십시오. 사실 전화의 편의를 위해 이 대화 상자를 구성 요소로 캡슐화했습니다. 구성 요소를 캡슐화하는 방법을 묻는 질문이 있습니까? 공식 튜토리얼로 이동해주세요:

https://developers.weixin.qq.com/miniprogram/dev/framework/custom-comComponent/

패키징이 완료된 후 프로젝트 구조는 다음과 같습니다:

맞춤형 WeChat 애플릿 구성요소(모달 팝업 구성요소)에 대한 자세한 설명

여기서 오해가 명확하게 설명될 것입니다. 표정을 짓고 계속 읽어주세요. .

세왕이 표시되어 있는데, 표시되지 않은Dialog.json 파일이 있습니다. 이 파일은 매우 간단합니다.

{
  "component": true,//作为组件
  "usingComponents": {}//引用别的组件
}

이 파일도 일반 json 파일과 다른 점은 주로 기타용 컴포넌트로 구성되어 있습니다. 참조하기 위해 이 구성 요소가 캡슐화되었습니다

아마도 이때 많은 어린이들이 코드를 복사하여 붙여넣고 프로젝트에 넣어 실제 결과가 다르다는 것을 알게 됩니다. 그렇다면 일부 사람들은 다음과 같이 말할 수 있습니다. Niang Xipi는 실제로 병행 수입업자이자 거짓말쟁이입니다! ! ! 이 시점에서 저는 단지 이렇게 말할 수 있습니다: 친애하는 여러분, 댄딩, 댄딩. . . , js에는 dataObject와 Bean이 없기 때문에 렌더링이 기사 시작 부분에 보여드린 것과 다릅니다. 그럼 어떻게 호출해서 저와 같은 효과를 얻을 수 있는지 알려드리겠습니다.

참조된 xml에 다음 코드를 추가하세요

<image src="../../img/add.png" class="buttom" bindtap="bindAdd"></image>

<dialog id=&#39;dialog&#39; title=&#39;新增&#39; bind:confirmEvent="_confirmEvent"></dialog>

buttom 이것은 플로팅 버튼이고, wxss도

.buttom{
  width: 100rpx;
  height: 100rpx;
  display: flex;
  flex-direction: row;
  position: fixed;
  bottom:60rpx;
  right: 60rpx;
}

를 제공합니다. 그런 다음 참조 페이지의 js 파일에서

onReady: function() {
    //获得dialog组件
    this.dialog = this.selectComponent("#dialog");
}



//响应button弹框
bindAdd: function(e) {
    this.dialog.setDataObj(addObject, {})
    this.dialog.showDialog();
}

이 시점에서 기본적으로 플로팅 버튼을 클릭하면 실현됩니다. 팝업 상자. 일부 가슴이 큰 데이가 다시 말했습니다: 이봐요, 잠깐만요, addObject, 그리고 그 add.png는 아직 제공되지 않았습니다. 알았어 줘 줘

const addObject = [{
  id: "name",
  must: true,
  placeholder: "姓名",
  type: "input",
  event: "nameInput"
},
{
  id: "sex",
  must: true,
  placeholder: "男",
  type: "button",
  event: "sexButton"
},
{
  id: "group",
  must: true,
  placeholder: "组织",
  type: "button",
  event: "groupButton"
},
{
  id: "phone",
  must: true,
  placeholder: "电话号码",
  type: "input",
  event: "phoneInput"
},
{
  id: "shortNum",
  must: false,
  placeholder: "集团短号",
  type: "input",
  event: "shortNumInput"
},
{
  id: "mail",
  must: false,
  placeholder: "电子邮箱",
  type: "input",
  event: "mailInput"
},
{
  id: "unit",
  must: false,
  placeholder: "单位名称",
  type: "input",
  event: "unitInput"
},
{
  id: "department",
  must: false,
  placeholder: "部门名称",
  type: "input",
  event: "departmentInput"
},
{
  id: "job",
  must: false,
  placeholder: "职务",
  type: "input",
  event: "jobInput"
},
{
  id: "function",
  must: false,
  placeholder: "涉及工作内容",
  type: "input",
  event: "functionInput"
},
{
  id: "comPhone",
  must: false,
  placeholder: "办公电话",
  type: "input",
  event: "comPhoneInput"
},
{
  id: "fax",
  must: false,
  placeholder: "传真",
  type: "input",
  event: "faxInput"
},
{
  id: "homePhone",
  must: false,
  placeholder: "家庭电话",
  type: "input",
  event: "homePhoneInput"
},
{
  id: "showOrder",
  must: false,
  placeholder: "显示顺序",
  type: "input",
  event: "showOrderInput"
},
{
  id: "departOrder",
  must: false,
  placeholder: "部门顺序",
  type: "input",
  event: "departOrderInput"
},
{
  id: "remark",
  must: false,
  placeholder: "备注",
  type: "input",
  event: "remarkInput"
}
]

picture

맞춤형 WeChat 애플릿 구성요소(모달 팝업 구성요소)에 대한 자세한 설명

이제 저와 같은 효과를 얻으실 수 있을 테니 마음껏 가지고 놀아보세요.

관련 기사:

WeChat 미니 프로그램의 사용자 정의 모달 팝업 창 예에 대한 자세한 설명

WeChat 미니 프로그램 - 사용자 정의 생성

관련 동영상:

WeChat 미니 프로그램 개발 초보자부터 숙달까지 비디오 튜토리얼

위 내용은 맞춤형 WeChat 애플릿 구성요소(모달 팝업 구성요소)에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.