表情包 - vue/微信小程序/js/数据驱动

3,332 阅读1分钟

一、先放效果图

先放效果图

二、介绍

实现起来比较简单,是用了微信的表情包地址,更改对应的表情dom节点。然后用v-html渲染

三、实现/原理

  • 先把表情包展示出来

    这里有个数组,文字对应的下标就是微信表情包的表情名称。 比如,第i个表情下标是index,对应微信表情包的地址为:

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

    这样就很简单了,直接初始化表情包

    注意:我这里把对应的文字更改为以#号开头,;号结尾。一定规则的字符串,方便拿到数据进行解析。为什么不直接储存标签呢,是因为还要在输入框展示啊!!如果能做成输入框也展示正常表情那就更好了,欢迎大佬留言!!!

     // 初始化表情
     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
                }
               }
            );