vue中自定義組件的用法(企業微信通訊錄選人)

組件的好處就是可以重複使用,壞處就是父子組件之間的通信相對比較麻煩,但是掌握了父子組件之間的通信後組件的應用就很簡單了。下面是實戰,最後是思路。

項目的index.html中引入https://res.wx.qq.com/open/js/jweixin-1.2.0.js">

1.子組件

<template>
  <div class="add-photo-con">
    <div class="photo-icon-con" :key="item.id" v-for="item in selectedUserList">
      <div class="del-phone-icon">
        <img class="" style="height: 100%;width: 100%;" @click="delPic(item.id)" src="../assets/images/m-del-red.png">
      </div>
      <div class="add-photo-icon1">
        <img class="add-photo-icon1" v-if="item.avatar" :src="item.avatar">
        <img class="add-photo-icon1" v-else src="../assets/images/m-head-sculpture-default.png">
      </div>
   </div>
   <img @click="selectMeetingUsers" class="add-photo-icon" src="../assets/images/m-add-photo.png">
 </div>
</template>
<style scoped>
  .add-photo-icon {
    width: 30px;
    height: 30px;
    margin-right: 10px;
  }
  .add-photo-icon1 {
    width: 45px;
    height: 45px;
    border-radius: 3px;
  }
  .del-phone-icon{
    height: 12px;
    width: 12px;
    margin-left: 38px;
    margin-bottom: -5px;
    z-index: 10;
  }
  .photo-icon-con{
    width: 45px;
    height: 45px;
    margin-right: 10px;
    margin-bottom: 10px;
    display: flex;
    flex-direction: column;
  }
  .add-photo-con {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: flex-start;
    align-items: center;
    padding-left: 10px;
    padding-top: 10px;
  }
  .textarea-title {
    font-size: 14px;
    font-family: "Microsoft YaHei";
    font-weight: 500;
    color: #434343;
    line-height: 28px;
  }
  .textarea-title:before {
    content: "* ";
    color: #FF0000;
  }
  .textarea-con {
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: flex-start;
    background: #ffffff;
    padding: 5px 10px;
    border-bottom: 1px solid #f2f2f2;
  }
</style>
<script>
  export default {
    name: 'selectComponents',
    props:{
      name: {
        type: String
      }
    },
    data() {
      return {
        selectedUserList: [],
        selectedUserIds: [],
      }
    },
    methods: {
      getpeopleArrList(val){
        this.selectedUserList = val
        this.getSelectedUserIds();
      },
      delPic(id){
        for(let i=0; i<this.selectedUserList.length; i++){
          if(this.selectedUserList[i].id == id){
            this.selectedUserList.splice(i, 1);
          }
        }
        this.getSelectedUserIds();
        this.invokeEmit();
      },
      selectMeetingUsers () {
        var that = this;
        wx.invoke("selectEnterpriseContact", {
            "fromDepartmentId": -1,// 必填,表示打開的通訊錄從指定的部門開始展示,-1表示自己所在部門開始, 0表示從最上層開始
            "mode": "multi",// 必填,選擇模式,single表示單選,multi表示多選
            "type": ["department", "user"],// 必填,選擇限制類型,指定department、user中的一個或者多個
            "selectedDepartmentIds": [],// 非必填,已選部門ID列表。用於多次選人時可重入,single模式下請勿填入多個id
            "selectedUserIds": that.selectedUserIds // 非必填,已選用戶ID列表。用於多次選人時可重入,single模式下請勿填入多個id
          },function(res){
            if (res.err_msg == "selectEnterpriseContact:ok")
            {
              if(typeof res.result == 'string')
              {
                res.result = JSON.parse(res.result) //由於目前各個終端尚未完全兼容,需要開發者額外判斷result類型以保證在各個終端的兼容性
              }

              that.selectedUserList = res.result.userList; // 已選的成員列表
              that.getSelectedUserIds();
              that.invokeEmit();
            }
          }
        );
      },
      getSelectedUserIds(){
        this.selectedUserIds = [];
        for (var i = 0; i < this.selectedUserList.length; i++)
        {
          var user = this.selectedUserList[i];
          this.selectedUserIds.push(user.id); // 已選的單個成員ID
        }
      },
      invokeEmit(){
        var that = this;
        if(this.name == 'person'){
          that.$emit('getPersonList', that.selectedUserList)
        }else if(this.name = 'leader'){
          that.$emit('getLeaderList', that.selectedUserList)
        }
      }
    },
    mounted() {

    }
  }
</script>

2.父組件

<template>
	<div class="textarea-con">
        <div class="textarea-title">參會人員</div>
        <select-child @getPersonList="getPersonList" ref="peopleArr" :name="'person'"></select-child>
      </div>
</template>
<script>
import selectChild from '@/components/selectComponents'
import { initWxConfig } from '@/pub/js/initWxConfig'
 export default {
    components:{
      'select-child': selectChild
    },
    name: 'meetingApply',
    data() {
	    return {
	    	peoples: [],
		}
	},
    methods: {
		getPersonList(value){
	        this.peoples = value
	      },
	}mounted() {
      initWxConfig(this);
    }
   }
</script>

3.initWxConfig

/* 企業微信js配置 */
//注意:如果要在頁面調用企業微信內部方法,請現在下面的jsApiList數組中添加方法
import { Toast } from 'mint-ui'
export function initWxConfig(vm){
  var that = vm;
  var token = vm.util.getCookie('hbzy-user-token')
  // var url = encodeURIComponent(location.href)
  var url = 'https://weixin.hbtobacco.cn/hbwebchat/meeting/'
  vm.axios({
    url: '獲取簽名的後臺服務地址='+ token + '&url=' + url
  })
  .then( (response) => {
    // console.log(JSON.stringify(response))
    if(response.status == 200){
      var timestamp = response.data.timestamp //時間戳
      var nonceStr = response.data.nonceStr //隨機字符串
      var signature = response.data.signature //簽名
      var appId = response.data.appId //企業id

      wx.config({
        beta: true,// 必須這麼寫,否則wx.invoke調用形式的jsapi會有問題
        debug: false, // 開啓調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時纔會打印。
        appId: appId, // 必填,企業微信的corpID
        timestamp: timestamp, // 必填,生成簽名的時間戳
        nonceStr: nonceStr, // 必填,生成簽名的隨機串
        signature: signature,// 必填,簽名,見附錄1
        jsApiList: ['selectEnterpriseContact'] // 必填,需要使用的JS接口列表,所有JS接口列表見附錄2
      });
      wx.ready(function () {
      });
      wx.error(function(res){
        Toast('initWxConfig:'+JSON.stringify(res))
      });
    }else{
        Toast('else='+response.data.status_msg)
    }
  })
  .catch( (error) => {
    Toast('catch='+JSON.stringify(error))
  });
}

注意:

1.子組件建好後,然後在父組件中導入並註冊
2.父組件中有一個值:name="'leader'",子組件可以通過 props屬性取得,這裏傳值只是爲了告訴讀者子組件如何獲取父組件的值
3.由於在父組件中已經引入了子組件,在點擊組件的時候觸發的是子組件中的selectMeetingUsers方法(在企業微信api調用的文章中),選擇並顯示圖片,delPic方法爲刪除圖片
4.最後調用invokeEmit方法通過 this.$emit('getPersonList', this.selectedUserList)將selectedUserList數組傳遞到父組件的getPersonList
最後說一句:props和this.$emit纔是關鍵
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章