使用IntersectionObserver实现通讯簿组件demo(vue)

目录

一、准备

0、首先,先下载一个后面需要用到的包:

1、在utils.js中准备几个用处理数据的函数:

二、开始

0、布局,初始化数据

1、点击右侧字母导航栏,滚动到相应位置

2、鼠标滚动到相应位置,右侧字母导航栏的选中项也相应改变

三、完整代码

0、组件调用代码:

1、组件代码:


只需要把展示数组数据给组件,组件就会按照拼音首字母分组排列,且右边字母导航栏会有相应样式变化。点击右侧字母导航栏,会滚动到相应的分组。

一、准备

0、首先,先下载一个后面需要用到的包:

// 下载
npm i js-pinyin

// 引入
import pinyin from 'js-pinyin'

// 它可以用于根据中文生成拼音
// console.log(pinyin.getFullChars('管理员'));  GuanLiYuan

1、在utils.js中准备几个用处理数据的函数:

import pinyin from 'js-pinyin'


/**
 * 
 * @returns 生成随机字符串
 */
export function getUUID () {
  function rx () {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }
  return `node_${+new Date()}_${rx()}${rx()}`;
}

/**
 * 
 * @returns 生成a-z+#的数组
 */
export function getLetters () {
  return Array.from({ length: 26 }, (v, i) => String.fromCharCode(65 + i)).concat(["#"])
}


/**
 * 
 * @param {*} number 生成通讯簿数据
 */
export function generateRandomName (number = 100) {
  const names = [
    "张", "李", "王", "刘", "陈", "杨", "赵", "黄", "周", "吴",
    "徐", "孙", "胡", "朱", "高", "林", "何", "郭", "马", "罗",
    "梁", "宋", "郑", "谢", "宋", "唐", "韩", "郑", "吴", "徐",
    "吕", "张", "朱", "刘", "陈", "杨", "赵", "黄", "周", "吴",
    "徐", "孙", "胡", "朱", "高", "林", "何", "郭", "马", "罗",
    "阿", "奥", "邓", "鄂", "お", "ま"
  ];
  function firstName () {
    return names[Math.floor(Math.random() * names.length)]
  }

  function lastName (i) {
    return String.fromCharCode(0x4e00 + (i * 2)) + names[Math.floor(Math.random() * names.length)]
  }

  return Array.from({ length: number }, (v, i) => {
    return {
      id: getUUID(),
      name: firstName() + lastName(i)
    }
  })

}


/**
 * 获取汉字首字母
 * @param {*} str 汉字
 */
export function initialLetter (str) {
  return pinyin.getFullChars(str)?.substring(0, 1)
}

二、开始

这个组件,只要完成两个任务就算完成了:1、点击右侧字母导航栏,滚动到相应位置。2、鼠标滚动到相应位置,右侧字母导航栏的选中项也相应改变。

0、布局,初始化数据

       组件初始代码:

<template>
  <div class="contacts">
    <div class="contacts-list">
      <el-checkbox-group v-model="checkList">
        <div
          class="key-group"
          v-for="(value, key, index) in groupData"
          :key="index"
        >
          <div class="group-title" :id="key">{{ key }}</div>
          <div class="checkbox-ul">
            <el-checkbox
              :label="item.name"
              v-for="item in value"
              :key="item.id"
            ></el-checkbox>
          </div>
        </div>
      </el-checkbox-group>
    </div>
    <div class="contacts-nav">
      <span
        v-for="letter in lettersArr"
        :key="letter"
        :class="[letter, current === letter ? 'active' : '']"
        @click="onChange(letter)"
        >{{ letter }}</span
      >
    </div>
  </div>
</template>
<script>
import { getLetters, initialLetter } from "@/utils"
let that
export default {
  name: "ContactsList",
  props: {
    list: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      lettersArr: getLetters(),// 右侧导航字母
      current: "A",// 默认选中的字母
      checkList: [],// 通讯簿选中的数据
      groupData: null,// 通讯簿数据
    }
  },
  methods: {
    setGroupData() {
      let resultList = {}
      let group = this.list.reduce((t, v) => {
        let initial = initialLetter(v.name)
        initial = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".includes(initial) ? initial : "#"
        if (t[initial]) {
          t[initial].push(v)
        } else {
          t[initial] = [v]
        }
        return t
      }, {})
      // 排序
      this.lettersArr.forEach((item) => {
        if (group[item]) {
          resultList[item] = group[item]
        }
      })
      this.groupData = resultList
    },
    // 点击右侧导航字母
    onChange(letter) {},
  },
  mounted() {
    this.setGroupData()
  },
}
</script>
<style lang="scss" scoped>
.contacts {
  width: 380px;
  height: 500px;
  display: flex;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
  box-sizing: border-box;
  &-list {
    position: relative;
    flex: 1;
    padding: 12px 10px;
    height: 100%;
    overflow-y: auto;
    &::-webkit-scrollbar {
      display: none;
    }
    .key-group {
      margin-bottom: 20px;
      .group-title {
        position: relative;
        color: #cec7d0;
        font-size: 14px;
        &::after {
          content: " ";
          position: absolute;
          top: 50%;
          left: 20px;
          width: calc(100% - 26px);
          height: 1px;
          background-color: #cec7d0;
        }
      }
      .checkbox-ul {
        display: flex;
        flex-direction: column;
        .el-checkbox {
          padding: 2px 5px;
          border-radius: 4px;
          margin-right: 0;
          &:hover {
            background-color: #f7f4f8;
          }
        }
      }
    }
  }
  &-nav {
    padding: 5px 0;
    display: flex;
    flex-direction: column;
    flex-wrap: wrap;
    align-content: center;
    width: 36px;
    font-size: 16px;
    font-weight: 500;
    color: #cec7d0;
    cursor: pointer;
    .active {
      color: #0052cc;
    }
  }
}
</style>

组件调用:

<template>
  <div class="contacts-page">
    <contacts-list :list="list" />
  </div>
</template>
<script>
import { generateRandomName } from "@/utils/methods"
import ContactsList from "@/components/ContactsList"
export default {
  name: "ContactsPage",
  data() {
    return {
      list: generateRandomName(200)
    }
  },
  components: { ContactsList }
}
</script>
<style lang="scss" scoped>
.contacts-page {
  padding-top: 100px;
  display: flex;
  justify-content: center;
  width: 100%;
  height: 100%;
  background-color: #aaa8a8;
}
</style>

// generateRandomName 函数可生成假数据,格式如下:
[{id:'123',name:'张三'},{id:'456',name:'李四'}]



// setGroupData 函数可把上面的数据按拼音首字母分组,格式如下(如果不属于字母,归类于#号):
{
    A:[{id:'001',name:'埃勒苏'},{id:'009',name:'阿勒苏'}],
    B:[{id:'008',name:'布达拉'}],
    #:[{id:'007',name:'お小日'}]
}


如上,我们就把展示和样式和数据写好了,接下来专心于逻辑即可。

1、点击右侧字母导航栏,滚动到相应位置

(这个可以有很多种写法,比如在渲染完成后获得每一个数据组距离顶部的距离,保存在数组,点击导航字母滚动相应的距离数即可。使用锚链接,给每个数据组盒子一个id,用a链接或者window.location.hash跳转到这个id即可,这不是一个好方法,这里仅做demo展示。)

给右侧字母导航盒子加上如下点击事件即可:

// 切换到指定字母区域
    onChange(letter) {
      this.current = letter
      if (Object.keys(this.groupData).includes(letter)) {
        window.location.hash = `#${letter}`
      }
    },

2、鼠标滚动到相应位置,右侧字母导航栏的选中项也相应改变

(在用for循环生成数据组的时候,我们给了每个数据组的盒子一个id,我们只需要在滚动到某个数据组盒子的时候,更新右侧导航字母选中值即可。)

HTML5给我们提供了一个构造函数(IntersectionObserver),它可以监测一个元素随着滚动条的滚动有没有进入到另一个元素内(和元素重叠)。

我们在组件的methods内定义这个函数:


observer() {
      const obArr = document.querySelectorAll(".group-title")
      // 建立观察者,第一个参数是一个函数,代表重叠了要做什么
      this.ob = new IntersectionObserver(fn, {
        root: document.querySelector(".contacts"), // 填root:null或者直接不传这个参数的话,就代表以可视窗口为参考
        thresholds: 1, // 取值为0-1之间,代表观察元素进入到参考元素的哪个位置时触发,0.1是刚刚开始,0.5是进入一半,1是完全进入
        rootMargin: "300px 0px" // 上中下右,rootMargin扩大了元素的感知范围,如果为100px,说明元素距离交叉位置还有100px就代表已交叉,如果为-100px,代表元素超过交叉范围100px才算交叉,一般用正值,如图片预加载等等,及图片还没到可视区域,先加载出来
      })
      // 观察
      obArr.forEach((el) => {
        this.ob.observe(el)
      })
      function fn(entries) {
        // console.log(entries[0].isIntersecting); // 离开时为false,进入时为true(进入视口区域时是true,离开视口区域时是false。注意,刚开始加载时会触发一次,是false)
        if ( entries[0].isIntersecting) {
          that.current = entries[0].target.id
        }
      }
    }

在mounted中调用函数:

mounted() {
    this.setGroupData()
    this.$nextTick(() => {
      that = this
      this.observer()
    })
  },

在beforeDestroy生命周期取消监听:

beforeDestroy() {
    // 取消监听
    if (this.ob) {
      this.ob.disconnect()
    }
  }

三、完整代码

0、组件调用代码:

<template>
  <div class="contacts-page">
    <contacts-list :list="list" />
  </div>
</template>
<script>
import { generateRandomName } from "@/utils"
import ContactsList from "@/components/ContactsList"
export default {
  name: "ContactsPage",
  data() {
    return {
      list: generateRandomName(200)
    }
  },
  components: { ContactsList }
}
</script>
<style lang="scss" scoped>
.contacts-page {
  padding-top: 100px;
  display: flex;
  justify-content: center;
  width: 100%;
  height: 100%;
  background-color: #aaa8a8;
}
</style>

1、组件代码:

<template>
  <div class="contacts">
    <div class="contacts-list">
      <el-checkbox-group v-model="checkList">
        <div
          class="key-group"
          v-for="(value, key, index) in groupData"
          :key="index"
        >
          <div class="group-title" :id="key">{{ key }}</div>
          <div class="checkbox-ul">
            <el-checkbox
              :label="item.name"
              v-for="item in value"
              :key="item.id"
            ></el-checkbox>
          </div>
        </div>
      </el-checkbox-group>
    </div>
    <div class="contacts-nav">
      <span
        v-for="letter in lettersArr"
        :key="letter"
        :class="[letter, current === letter ? 'active' : '']"
        @click="onChange(letter)"
        >{{ letter }}</span
      >
    </div>
  </div>
</template>
<script>
import { getLetters, initialLetter } from "@/utils"
let that
export default {
  name: "ContactsList",
  props: {
    list: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      lettersArr: getLetters(),
      current: "A",
      checkList: [],
      groupData: null,
      ob: null
    }
  },
  methods: {
    setGroupData() {
      let resultList = {}
      let group = this.list.reduce((t, v) => {
        let initial = initialLetter(v.name)
        initial = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".includes(initial) ? initial : "#"
        if (t[initial]) {
          t[initial].push(v)
        } else {
          t[initial] = [v]
        }
        return t
      }, {})
      // 排序
      this.lettersArr.forEach((item) => {
        if (group[item]) {
          resultList[item] = group[item]
        }
      })
      this.groupData = resultList
    },
    // 切换到指定字母区域
    onChange(letter) {
      this.current = letter
      if (Object.keys(this.groupData).includes(letter)) {
        window.location.hash = `#${letter}`
      }
    },
    observer() {
      const obArr = document.querySelectorAll(".group-title")
      // 建立观察者,第一个参数是一个函数,代表重叠了要做什么
      this.ob = new IntersectionObserver(fn, {
        root: document.querySelector(".contacts"), // 填root:null或者直接不传这个参数的话,就代表以可视窗口为参考
        thresholds: 1, // 取值为0-1之间,代表观察元素进入到参考元素的哪个位置时触发,0.1是刚刚开始,0.5是进入一半,1是完全进入
        rootMargin: "300px 0px" // 上中下右,rootMargin扩大了元素的感知范围,如果为100px,说明元素距离交叉位置还有100px就代表已交叉,如果为-100px,代表元素超过交叉范围100px才算交叉,一般用正值,如图片预加载等等,及图片还没到可视区域,先加载出来
      })
      // 观察
      obArr.forEach((el) => {
        this.ob.observe(el)
      })
      function fn(entries) {
        // console.log(entries[0].isIntersecting); // 离开时为false,进入时为true(进入视口区域时是true,离开视口区域时是false。注意,刚开始加载时会触发一次,是false)
        if ( entries[0].isIntersecting) {
          that.current = entries[0].target.id
        }
      }
    }
  },
  mounted() {
    this.setGroupData()
    this.$nextTick(() => {
      that = this
      this.observer()
    })
  },
  beforeDestroy() {
    // 取消监听
    if (this.ob) {
      this.ob.disconnect()
    }
  }
}
</script>
<style lang="scss" scoped>
.contacts {
  width: 380px;
  height: 500px;
  display: flex;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
  box-sizing: border-box;
  &-list {
    position: relative;
    flex: 1;
    padding: 12px 10px;
    height: 100%;
    overflow-y: auto;
    &::-webkit-scrollbar {
      display: none;
    }
    .key-group {
      margin-bottom: 20px;
      .group-title {
        position: relative;
        color: #cec7d0;
        font-size: 14px;
        &::after {
          content: " ";
          position: absolute;
          top: 50%;
          left: 20px;
          width: calc(100% - 26px);
          height: 1px;
          background-color: #cec7d0;
        }
      }
      .checkbox-ul {
        display: flex;
        flex-direction: column;
        .el-checkbox {
          padding: 2px 5px;
          border-radius: 4px;
          margin-right: 0;
          &:hover {
            background-color: #f7f4f8;
          }
        }
      }
    }
  }
  &-nav {
    padding: 5px 0;
    display: flex;
    flex-direction: column;
    flex-wrap: wrap;
    align-content: center;
    width: 36px;
    font-size: 16px;
    font-weight: 500;
    color: #cec7d0;
    cursor: pointer;
    .active {
      color: #0052cc;
    }
  }
}
</style>

以上,把代码复制可直接运行demo。

在生产环境中在完成第一步时,不建议直接使用锚链接window.location.hash跳转到相应位置。如果使用的框架是vue或者react,路由使用的是hash Router,那么url就会和路由有冲突。而且这种滚动只能让盒子贴到组件的顶部,如果说想点击导航字母"C",让C组数据滚动到组件中部,这种方法就做不到,不够灵活。可以考虑使用自己控制滚动距离的方式。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值