表情包 - vue/微信小程序/js/數據驅動

1、先放效果圖

先放效果圖

2、介紹

實現起來比較簡單,是用了微信的表情包地址,更改對應的表情dom節點。而後用v-html渲染html

3、實現/原理

  • 先把表情包展現出來

    這裏有個數組,文字對應的下標就是微信表情包的表情名稱。 好比,第i個表情下標是index,對應微信表情包的地址爲:git

    const img = `<img src="https://res.wx.qq.com/mpres/htmledition/images/icon/emotion/${index}.gif" />`
    複製代碼

    這樣就很簡單了,直接初始化表情包

    注意:我這裏把對應的文字更改成以#號開頭,;號結尾。必定規則的字符串,方便拿到數據進行解析。爲何不直接儲存標籤呢,是由於還要在輸入框展現啊!!若是能作成輸入框也展現正常表情那就更好了,歡迎大佬留言!!!github

    // 初始化表情
     initEmotion(){
       const list = this.emotionList;
       let emotionArr = [];
       list.map((item, index) => {
         emotionArr.push({
           name: `#${item};`,
           url: `<img src="https://res.wx.qq.com/mpres/htmledition/images/icon/emotion/${index}.gif">`
         });
       });
       this.emotionArr = emotionArr;
     },
    複製代碼

    拿到帶有表情地址的數組,知道怎麼渲染了吧

    <div v-for="(line, i) in emotionArr" :key="i" @click="handEmotion(line)">
    </div>
    複製代碼

    而後點擊的時候直接插入到輸入框

    handEmotion(item) {
      this.sendInfo += item.name;
    }
    複製代碼
  • 插入到輸入框光標位置

    ```
      //.....
      
      //這個問題問的好!
      ```
    複製代碼
  • 獲取並展現表情包的消息內容

    請求數據的拿到,應該是咱們以前爲表情作了特殊修改的字符串,好比"hello world#你好;"裏面的#你好;就應該轉成表情地址,而後再渲染出來。正則表達式

    正則表達式/\#[\u4E00-\u9FA5]{1,3}\;/gi: 意思就是,以#開頭;結尾的字符,中間可有1-3個字符數組

    // 將匹配結果替換表情圖片
            item.Info = item.Info.replace(
              /\#[\u4E00-\u9FA5]{1,3}\;/gi,
              words => {
                let word = words.replace(/\#|\;/gi, "");
                let index = this.emotionList.indexOf(word);
                if(index!== -1){ 
                  return `<img src="https://res.wx.qq.com/mpres/htmledition/images/icon/emotion/${index}.gif" align="middle">`;
                }else{
                  return words
                }
               }
            );
    複製代碼
相關文章
相關標籤/搜索