其他分享
首页 > 其他分享> > vue基于textarea 实现@人的功能

vue基于textarea 实现@人的功能

作者:互联网

此需求来源于一个pc端的网页,要求用户打出@的时候 能够出现候选人列表,当点击其中一个之后,文字则显示@xxxx

应产品要求

   1,当删除'@xxx'中其中的任意一个字符或字符串的时候 '@xxx' 这段字符串均被删除

   2,'@xxx'字符串中不得穿插其他内容 即当用户光标在'@xxx'中输入的时候,是无效的

思路:1,  首先绑定textarea v-model="text"

           2,  标记@出现的地方 这里我采用' `@ ' 标记选人开始的地方,选人完成后 @xxx 最后一个 x 标记为 ' x` '  ,那么根据 ` 开始 和` 结束 则标记了 一个完成的@xxxx 字段,这里我维护为一个数组

           3,删除的时候,

                      1i, 普通删除 :即删除非@xxx的字符或字符串

                      2i,删除@xxx当中的字符或字符串

                      3i ,关键是对比 看删除的内容是什么 从哪里开始 删除的长度是多少

           4,正是因为每次操作是单一连续的(即每次的操作均在某处插入或删除而非多处,这样就只需要维护两个变量,插入的位置和数量),所以才有可能完成此需求

预备知识: 1,textarea获取当前光标的位置 dom.selectionStart

                   2,  vue动态监听操作,有时候我们认为某一次的操作不应该触发watch,这时会采用动态监听如下, $watch会返回一个watcher函数 当我们调用他的时候 会取消掉vue对text的监听

                    

registerWatch() {
   this.watcher = this.$watch('text',function(cv,ov) {
          //xxxxx
     })

}     

     //操作text的方法
     handleTextOptions() {
         // 我们认为本次不需要监听text
        this.watcher()
        this.text = xxx
    }
     // 预先

           3, 维护一个

下面贴代码 

           

<template>
  <div id="app">
    <div class="btncontainer">
      <textarea
        id="textarea"
        @keydown="handleKeyDown"
        v-model="text"
        @input.prevent="handleInput"
        @focus="handleFocus"
        @mouseup="handleMouseUp"
      ></textarea>
      <div class="board" v-show="showboard">
        <div
          v-for="(item, index) in list"
          @click="handleItemClick(index)"
          :key="index"
        >
          {{ item.name }}
        </div>
      </div>
    </div>

    <router-view />
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      env: process.env.NODE_ENV,
      active: 0,
      text: "",
      showboard: false,
      list: [],
      tempinput: "",
      markselectpeople: false, // 标记开始选人
      markdisable: false,
      unwatch: () => {},
      operationindex: null,
      oldtext: "",
      textlist: [],
    };
  },
  mounted() {
    window.vm0 = this;
    this.watchText();
    for (let j = 0; j < 20; j++) {
      let item = {
        name: "王尼玛" + j,
        id: j,
      };
      this.list.push(item);
    }
  },
  methods: {
    watchText() {
      this.unwatch = this.$watch("text", function (cv, ov) {
        if (ov.length > cv.length) {
          let ovlist = [...ov];
          let cvlist = [...cv];
          let startremove = this.findDiffStart(cv, ov);
          let removestr = "";
          let difflength = ovlist.length - cvlist.length;
          for (let j = startremove; j <= startremove + difflength - 1; j++) {
            removestr += ovlist[j];
          }
          console.log("对比结果", startremove, ov, cv, removestr);
       
          console.log(removestr, "匹配器结果");
          let atnamelist = this.findAtNameList();
          console.log(
            "atnamelist",
            atnamelist,
            removestr,
            startremove
          );
          for (let j = 0; j < atnamelist.length; j++) {
            for (
              let k = atnamelist[j].startindex;
              k <= atnamelist[j].endindex;
              k++
            ) {
              if (k >= startremove && k <= startremove + removestr.length - 1) {
                atnamelist[j].remove = true;
              }
            }
          }
          let temp = [...ov];
          let tempstr = [...ov];
          let finalstr = "";
          let temptextlist = [...this.textlist];
          console.log("temp", temp);
          for (let j = 0; j < temp.length; j++) {
            // 拿出@xxx并标记
            for (let k = 0; k < atnamelist.length; k++) {
              if (
                atnamelist[k].remove &&
                j >= atnamelist[k].startindex &&
                j <= atnamelist[k].endindex
              ) {
                // 使用ᑒ特殊符号进行标记
                tempstr[j] = "ᑒ";
                temptextlist[j] = "ᑒ";
              }
            }
            // 拿出正常删除的并标记
            if (j >= startremove && j <= startremove + removestr.length - 1) {
              tempstr[j] = "ᑒ";
              temptextlist[j] = "ᑒ";
            }
          }
          for (let j = 0; j < tempstr.length; j++) {
            if (tempstr[j] != "ᑒ") {
              finalstr += tempstr[j];
            }
          }
          this.textlist = [];
          for (let j = 0; j < temptextlist.length; j++) {
            if (temptextlist[j] != "ᑒ") {
              this.textlist.push(temptextlist[j]);
            }
          }
          if (finalstr !== ov) {
            console.log("finalstr", finalstr);
            this.text = finalstr;
            console.log("之后的this.textlist", this.textlist);
            // 重新赋值 textlist
            this.unwatch();
            setTimeout(() => {
              this.watchText();
            });
          } else {
            // 此时校验长度
          }

          console.log(finalstr, "最终");
          this.markdisable = false;
        } else {
          if (this.markdisable) {
            this.text = ov;
            this.unwatch();
            this.watchText();
            return;
          }
          let startremove = this.findDiffForcvmoreOv(cv, ov);

          let removestr = "";
          let difflength = cv.length - ov.length;

          for (let j = startremove; j <= startremove + difflength - 1; j++) {
            removestr += cv[j];
          }
          console.log("对比结果" + removestr);
          let beforelinelist = this.textlist.slice(0, startremove);
          let endlinelist = this.textlist.slice(startremove);
          let namelist = [...removestr];
          this.textlist = [...beforelinelist, ...namelist, ...endlinelist];
        }
      });
    },
    // 当cv大于ov时不一样
    findDiffForcvmoreOv(cv, ov) {
      let shorter = ov;
      let longer = cv;
      let longerlist = [...longer];
      let shorterlist = [...shorter];
      let thestartindex = null;
      for (let j = 0; j < shorterlist.length + 1; j++) {
        let insertindex = j;
        for (let k = 0; k < longerlist.length; k++) {
          let sliced = longerlist.slice(k, k + longer.length - shorter.length);
          let begin = shorterlist.slice(0, j);
          let center = sliced;
          let end = shorterlist.slice(j);
          let finalstr = [...begin, ...center, ...end].join("");
          if (finalstr == longer) {
            return j;
          }
        }
      }
    },

    // 查找开始不同的index
    findDiffStart(cv, ov) {
      let str1 = ov;
      let str2 = cv;
      let str1list = [...str1];
      let str2list = [...str2];
      let thestartindex = null;
      for (let j = 0; j < str1list.length; j++) {
        let sliced = str1list.slice(j, j + str1.length - str2.length);
        let find = false;
        for (let k = 0; k < str2list.length; k++) {
          let beforestr = str2list.slice(0, j);
          let centerstr = sliced;
          let endstr = str2list.slice(j);
          console.log(
            [...beforestr, ...centerstr, ...endstr].join(""),
            "最终结果"
          );
          if ([...beforestr, ...centerstr, ...endstr].join("") == str1) {
            find = true;

            break;
          }
        }
        if (find) {
          thestartindex = j;
          console.log(j, "哈哈哈");
          break;
        }
      }
      return thestartindex;
    },
    setCaret() {
      var el = document.getElementById("editable");
      var range = document.createRange();
      var sel = window.getSelection();
      console.log(el.childNodes);
      range.setStart(el.childNodes[2], 1);
      range.collapse(true);

      sel.removeAllRanges();
      sel.addRange(range);
    },
    // 监听方向键
    handleKeyDown(e) {
      if (e.keyCode >= 37 && e.keyCode <= 40) {
        // alert(4)
        setTimeout(() => {
          console.log("位置", e.keyCode, e.target.selectionStart);
          let index = e.target.selectionStart - 1;
          console.log(index);
          let atgroup = this.findAtNameList();
          let disabled = false;
          for (let j = 0; j < atgroup.length; j++) {
            if (
              index >= atgroup[j].startindex &&
              index < atgroup[j].endindex &&
              index != this.text.length - 1
            ) {
              // e.target.selectionStart = atgroup[j].endindex
              // e.target.disabled = true
              disabled = true;
              break;
            }
          }
          this.markdisable = disabled;
        }, 5);
      }
    },
    // 处理鼠标左键按下
    handleMouseUp(e) {
      let index = e.target.selectionStart - 1;
      console.log(index);
      let atgroup = this.findAtNameList();
      let disabled = false;
      for (let j = 0; j < atgroup.length; j++) {
        if (
          index >= atgroup[j].startindex &&
          index < atgroup[j].endindex &&
          index != this.text.length - 1
        ) {
          // e.target.selectionStart = atgroup[j].endindex
          // e.target.disabled = true
          disabled = true;
          break;
        }
      }
      this.markdisable = disabled;
      e.stopPropagation();
      e.preventDefault();
    },
    handleFocus(e) {
      if (this.markselectpeople) {
        // 表明用户未选择内容
        this.textlist.splice(this.operationindex - 1, 0, "@");
        console.log("聚焦后的textlist", this.textlist);
        this.showboard = false;
        this.watchText();
        this.markselectpeople = false;
      } else {
        // 聚焦到非@xxxx的地方
        console.log(e.target.selectionStart, e.target.selectionEnd);
      }
      e.stopPropagation();
      e.preventDefault();
    },
    handleInput(e) {
      if (e.data == "@") {
        if (this.markdisable) {
          return;
        }
        this.showboard = true;
        this.markselectpeople = true;
        this.unwatch();
        setTimeout(() => {
          e.target.blur();
        }, 10);
        this.operationindex = e.target.selectionStart;
      } else {
        // this.placeCaretAtEnd(e.target);
        // e.target.selectionEnd= 2
        // var el = e.target;
        // var range = document.createRange();
        // console.log(range);
        // var sel = window.getSelection();
        // console.log(el.childNodes, "元素");
        // debugger;
        // range.setStart(el, 3);
        // range.collapse(true);
        // sel.removeAllRanges();
        // sel.addRange(range);
      }
      this.operationindex = e.target.selectionStart;
      console.log(this.operationindex);
      e.stopPropagation();
      e.preventDefault();
    },
    handleItemClick(index) {
      let textlist = [...this.text];
      let beforeline = textlist.slice(0, this.operationindex);
      let endline = textlist.slice(this.operationindex);
      console.log(beforeline, endline);
      this.text =
        beforeline.join("") + this.list[index].name + endline.join("");
      // console.log(JSON.stringify(this.textlist),"操作之前")
      this.textlist.splice(this.operationindex - 1, 0, "`@");
      // console.log(JSON.stringify(this.textlist),"插入之后")
      let beforelinelist = this.textlist.slice(0, this.operationindex);
      let endlinelist = this.textlist.slice(this.operationindex);
      let namelist = [...this.list[index].name];
      // console.log(beforelinelist,namelist,endlinelist)
      namelist[namelist.length - 1] = namelist[namelist.length - 1] + "`";
      this.textlist = [...beforelinelist, ...namelist, ...endlinelist];
      console.log("点击后的this.textlist:" + this.textlist);
      // TODO 添加响应式
      setTimeout(() => {
        this.watchText();
        this.showboard = false;
        this.markselectpeople = false;
      }, 10);
    },
    // 找寻@名称列表
    findAtNameList() {
      let atgroup = [];
      let textlist = this.textlist;
      let startindex = null;
      let endindex = null;
      console.log("findAtNameList", [...textlist]);
      for (let j = 0; j < textlist.length; j++) {
        if (textlist[j] == "`@") {
          startindex = j;
          // 开始标记
          // str += textlist[j]
          endindex = null;
        }
        if (textlist[j][textlist[j].length - 1] == "`") {
          // 结束符号
          if (startindex !== null) {
            endindex = j;
          }
        }
        if (startindex !== null && endindex !== null) {
          let item = {
            startindex: startindex,
            endindex: endindex,
          };
          startindex = null;
          endindex = null;
          atgroup.push(item);
        }
      }
      return atgroup;
    },
    goToHome() {
      if (this.$route.path == "/") {
        return;
      }
      this.$router.push({
        name: "HelloWorld",
      });
    },
    goToTest() {
      if (this.$route.path == "/Test") {
        return;
      }
      this.$router.push({
        name: "Test",
      });
    },
  },
};
</script>

<style lang="less">
#app {
  #editable {
    width: 100px;
    height: 100px;
  }
  .btncontainer {
    display: flex;
    textarea:disabled {
      background-color: white;
    }
    textarea {
      width: 200px;
      height: 200px;
    }
    .totest,
    .tohome {
      font-size: 12px;
      height: 30px;
      width: 80px;
      border: 1px solid gray;
      border-radius: 10px;
      margin-top: 10px;
      text-align: center;
      line-height: 30px;
      margin-left: 10px;
    }
    .text {
      width: 200px;
      height: 200px;
    }
    .board {
      width: 100px;
      max-height: 100px;
      overflow: scroll;
      cursor: pointer;
      .item {
        border-bottom: 1px solid gray;
        height: 20px;
        line-height: 20px;
        cursor: pointer;
      }
    }
  }
}
</style>

最终效果如下:

 

 

        

标签:基于,vue,console,log,textarea,text,let,textlist,target
来源: https://www.cnblogs.com/tony-stark/p/16116703.html