web開發技巧

1.user-select:none
場景:測試的同事常常跟咱們說,操做比較迅速的狀況下,頁面的元素總會有一層藍色,雖然不影響效果,可是不美觀。其實這是用戶選擇操做,瀏覽器自帶的,若是不想要改效果,能夠在元素容器設置css樣式user-select:none便可。css

2.特殊字符的正則匹配html

<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)當只替換第一個匹配的字符狀況下,沒有任何問題vue

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)全局替換,可是沒有將特殊字符轉義,報錯express

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
解決咱們要等待兩個或者多個異步操做完成在執行下一步操做的問題。session

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

<!-- 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)
相關文章
相關標籤/搜索