vue项目通讯录_vue组件--通讯录
簡介
在移動端開發中,通訊錄是個很常見的需求。
通訊錄通常要實現以下功能
首字母導航
滾動到一定位置首字母固定
布局
通訊錄是典型的上下兩欄布局,上面是header,下面是內容區,我們這里采用flexbox來實現。
html,body,.page{height: 100%}
.page{display: flex}
.page-header{height: 44px}
.page-content{
flex: 1;
overflow: auto;
-webkit-overflow-scrolling: touch;
}
.navs {
z-index: 2;
position: fixed;
right: 10px;
top: 50px;
bottom: 30px;
text-align: center;
color: #5d9ed3;
font-size: 10px;
display: flex;
flex-direction: column;
justify-content: space-between;
span {
cursor: pointer;
}
}
通訊錄Aa鏈家-張帶看a天團tonyOK。上面的代碼已經足夠定義一個頁面的雛形,
page-header 高度44,
page-content 占據剩余的全局的高度,并做內部的滾動。-webkit-overflow-scrolling: touch 會在容器里面開啟高性能滾動。
設置導航
頁面布局完成之后,可以初始化導航條了,為了方便起見,我們默認通訊錄里面包含了從A到Z的全部姓名。
文章默認使用 vue單文件組 件開發,如果您使用其他框架,請自行轉換代碼
{{item}}
data () {
return {
navs: "abcdefghijklmnopqrstuvwxyz".split("").map(i => i.toUpperCase());
}
}
建立索引
建立索引實際上是用js操作dom,獲取通訊錄內容區域內每個首字母出現的位置并存儲起來,方便做跳轉和滾動監聽。
moutend() {
// 因為要獲取dom屬性,所以要在組件render后執行
this.$nextTick(()=>{
this.body = this.$refs.content;
const navsEles = [...this.$refs.navs.querySelectorAll("span")]
const itemsEles = [...this.$refs.items.querySelectorAll(".item")]
// 獲取導航欄字母的高度信息,方便做點擊放大功能
this.navsOffset = navsEles.map(item=>{
return item.offsetTop || 0
})
// 獲取通訊錄內容區的首字母位置,方便做跳轉和滾動監聽
this.itemsOffset = itemsEles.map(item=>{
return item.offsetTop || 0
})
})
},
data () {
return {
body: null,
itemsOffset: [],
navsOffset: []
}
}
監聽跳轉
監聽跳轉比較簡單,在 .page-navs span 標簽上綁定click事件即可處理
{{item}}
methods: {
jump(index) {
// 因為offsetTop屬性是相對整個視口,而scrollTop是相對滾動容器,所以需要減去44px(header的高度)
const offset = this.itemsOffset[index] - 44;
this.body.scrollTop = offset;
}
},
data () {
return {
navs: "abcdefghijklmnopqrstuvwxyz".split("").map(i => i.toUpperCase());
}
}
監聽滾動
因為是在page-content元素內部滾動,所以可以通過在該元素上綁定scroll方法監聽頁面的滾動。局部滾動的好處是組件銷毀時事件監聽也移除了,不像監聽body的滾動還需要在銷毀前手動removeEventListenr。
在執行滾動監聽之前,我們還需要做兩件事情
對 itemsOffset 進行分組,劃定監聽的區間
在頁面頂部創建一個展示 當前聯系人首字母 的組件
// 當前聯系人首字母組件
// 在這個組件里面也創建一個列表,用來做滾動的動畫
{{item}}// 對 `itemsOffset` 進行分組,劃定監聽的區間
mounted() {
this.$nextTick(() => {
let offsetCalc = this.offset.slice();
offsetCalc.forEach((item, index) => {
this.offsetList.push([item, offsetCalc[index + 1]]);
});
});
}
data() {
return {
currentIndex: -1,
offsetList: []
}
}
在準備工作做好之后,就開始監聽容器的滾動行為,當滾動到通訊錄之中的首字母部分時, 聯系人首字母組件 也會自動滾動到里面相應的字母位置。
點擊右側導航,也會觸發滾動事件。
// html模板部分
// js部分
methods: {
scroll() {
this.currentIndex = this.getArea(this.body.scrollTop);
},
getArea(scrollTop) {
// 80是首字母標組件的高度+通訊錄首字母的高度
scrollTop += 80;
let index = -1;
for (let i = 0, size = this.offsetList.length; i < size; i++) {
let [start, end] = this.offsetList[i];
if (scrollTop >= start && scrollTop < (end || 999999)) {
index = i;
break;
}
}
return index
},
}
更多
點擊右側導航,有時候還要求在附近顯示一個放大的字母,用于提醒點擊了那個字母,通過前面獲取的 navsOffset ,可以很方便的實現這個需求。至此,整個通訊錄功能就基本完成了。
總結
以上是生活随笔為你收集整理的vue项目通讯录_vue组件--通讯录的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python滚动文本框_调整滚动Tkin
- 下一篇: vue全局引入openlayers_vu