表情包 - 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
                }
               }
            );
    复制代码
相关文章
相关标签/搜索