1

1.user-select:none
场景:测试的同事经常跟我们说,操作比较迅速的情况下,页面的元素总会有一层蓝色,虽然不影响效果,但是不美观。其实这是用户选择操作,浏览器自带的,如果不想要改效果,可以在元素容器设置css样式user-select:none即可。

2.特殊字符的正则匹配

 <template>
    <div>
        <h3>特殊字符的正则全局匹配</h3>
        <div @click="hanleReplace()">将特殊字符转化成123并标红</div>
        <p v-html="str"></p>
    </div>
</template>

<script>
export default {
    data() {
        return {
            str: '大师傅@$/::)sdfdhttp://的设计/::)费看::-Osf的数据反馈http://study.sxmaps.com给'
        }
    },
    methods: {
        hanleReplace() {
            let special = '/::)'
            //const transform = special.replace(/[.\\[\]{}()|^$?*+]/g, '\\$&');
            //let pattern = new RegExp(special, 'g');
            // let pattern = new RegExp(transform, 'g');
            let redText = '<span style="color: red">123</span>'
            this.str = this.str.replace(special, redText);
        },
    }
}
</script>

该列子是将特殊字符/::)替换成123并将字体颜色更改为红色,我们看看一下几种情况:
(1)当只替换第一个匹配的字符情况下,没有任何问题

    hanleReplace() {
        let special = '/::)'
        //const transform = special.replace(/[.\\[\]{}()|^$?*+]/g, '\\$&');
        //let pattern = new RegExp(special, 'g');
        // let pattern = new RegExp(transform, 'g');
        let redText = '<span style="color: red">123</span>'
        this.str = this.str.replace(special, redText);
    },

(2)全局替换,但是没有将特殊字符转义,报错

    hanleReplace() {
        let special = '/::)'
        //const transform = special.replace(/[.\\[\]{}()|^$?*+]/g, '\\$&');
        let pattern = new RegExp(special, 'g');
        // let pattern = new RegExp(transform, 'g');
        let redText = '<span style="color: red">123</span>'
        this.str = this.str.replace(pattern, redText);
    },
    //Invalid regular expression: //::)/: Unmatched ')'at new RegExp (<anonymous>)

(3)解决特殊字符的正则匹配,将特殊字符正则转义

    hanleReplace() {
        let special = '/::)'
        const transform = special.replace(/[.\\[\]{}()|^$?*+]/g, '\\$&');  //转义
        //let pattern = new RegExp(special, 'g');
        let pattern = new RegExp(transform, 'g');
        let redText = '<span style="color: red">123</span>'
        this.str = this.str.replace(pattern, redText);
    },

应用场景:(1)项目中展示微信聊天记录,解析微信发送的emoji。(2)根据关键字快速匹配聊天记录功能。
3.scrollIntoView快速定位到当前可见区域

在上拉加载更多聊天记录的时候,我们一般情况下是通过计算当前高度和加载后的高度相减以达到目的,用scrollIntoView不需要计算就能达到目的。
   <template>
     <div>
         <h3>ScrollIntoView</h3>
         <div class="chatBox" @scroll="handleScroll" id="chatBox">
         <div
            class="chatItem"
            v-for="item in chatList"
            :key="item"
            :id="`record${item.number}`"
          >
            {{ item.message }}
          </div>
        </div>
      </div>
    </template>
    
    <script>
    export default {
      data() {
        return {
          chatList: [],
          currentIndex: 0,
          scrollLoading: true,
          lastIndex: 0, //当前索引id
          currPagePos: 0, //当前内容高度
        };
      },
      created() {
        this.getData();
        this.$nextTick(() => {
          let chatBox = document.getElementById("chatBox");
          chatBox.scrollTop = chatBox.scrollHeight;
        });
      },
      methods: {
        //scrollIntoView
                handleScroll(e) {
                  if (e.target.scrollTop <= 5) {
                    this.lastIndex = this.chatList.length - 1;
                    this.getData();
                    setTimeout(() => {
                      const id = "record" + this.lastIndex;
                      document.getElementById(id).scrollIntoView();
                    }, 0);
                  }
                },
    
                // handleScroll(e) {
                //   if (e.target.scrollTop <= 5) {
                //     this.currPagePos = document.getElementById("chatBox").scrollHeight;
                //     this.getData();
                //     setTimeout(() => {
                //       let totalHeight = document.getElementById("chatBox").scrollHeight;
                //       document.getElementById("chatBox").scrollTop =
                //         totalHeight - this.currPagePos;
                //     }, 0);
                //   }
                // },
    
                //获取数据
                getData() {
                  let newList = [];
                  for (let i = 0; i < 20; i++) {
                    newList.unshift({
                      number: this.currentIndex,
                      message: "message" + this.currentIndex,
                    });
                    ++this.currentIndex;
                  }
                  this.chatList = newList.concat(this.chatList);
                },
              },
            };
            </script>
    
            <style scoped>
            .chatBox {
              width: 400px;
              height: 500px;
              border: 1px solid #f5f5f5;
              margin: 30px;
              overflow-y: scroll;
            }
            .chatItem {
              height: 100px;
              background: #f5f5f5;
              margin-top: 30px;
            }
            </style>
    

4.Promise.all
解决我们要等待两个或者多个异步操作完成在执行下一步操作的问题。

init(url) {
  const a = new Promise((resolve) => {
    initWxConfig(url).then(() => {
      window.wx.invoke("getCurExternalContact", {}, (res) => {
        console.log(res, 'userId')
       
        if (res.err_msg == "getCurExternalContact:ok") {
          //userId  = res.userId ; //返回当前外部联系人userId
          this.workWechatExternalUserId = res.userId;
     
          sessionStorage.setItem("workWechatExternalUserId", res.userId);
          
          resolve("ok");
        } else {
          //错误处理
        }
      });
    });
  });

  let b = new Promise((resolve) => {
    let userId = localStorage.getItem("userId");
    if (!userId) {
      sessionModel
        .workWechatgetuserinfo(this.$route.query.code)
        .then((res) => {
          this.workWechatUserId = res.userId;
          sessionStorage.setItem("userId", res.userId);

          resolve("成功");

        });
    } else {
      resolve("成功");
    }
  });

  Promise.all([a, b]).then(() => {
    let url = `${process.env.VUE_APP_HTTP_URL}/cuckoo/studentInformation`;
    window.history.replaceState(null,null,url)
    this.getMemberDetail();
  });
},

5.vue函数式组件
函数式组件,即无状态,无法实例化,内部没有任何生命周期处理方法,非常轻量,因而渲染性能比普通的高达70%,特别适合用来只依赖外部数据传递而变化的组件。

  <!-- App.vue -->
    <template>
      <div id="app">
        <List
          :items="['Wonderwoman', 'Ironman']"
          :item-click="item => (clicked = item)"
        />
        <p>Clicked hero: {{ clicked }}</p>
      </div>
    </template>
    
    <script>
    import List from "./List";
    
    export default {
      name: "App",
      data: () => ({ clicked: "" }),
      components: { List }
    };
    </script>

    
    <!-- List.vue 函数式组件 -->
    <template functional>
      <div>
        <p v-for="item in props.items" @click="props.itemClick(item);">
          {{ item }}
        </p>
      </div>
    </template>
    [7个有用的Vue开发技巧](https://juejin.cn/post/6844903848050589704)

    

带着代码去旅行
64 声望3 粉丝