其實我覺得很簡單,難點就2個。首先是滑動,這里用了better-scroll這個組件,可以在網上搜,挺好用的。另一個就是頁面布局的問題,寫點css還是沒得問題的。
首先去better-scroll的官網,按著他的核心邏輯抄一下。不詳細談了,總之來說,會有三層嵌套。我個人命名他們為: wrapper
和content
和 item
這三層。
先弄一個json,當做會被填充的數據。
export const chatItems = [ { type:1, message:"fdaf地方撒風大撒風阿斯頓飛fd阿斯頓飛安德森發大水發大水發大水奮斗發的大撒風安德森 發大發大水發", from:1, timestamp: new Date() }, { type:1, message:"fdaf地方撒風大撒aa風阿斯頓飛ffdsafsfadsfadsfjlkjsadflkosdajfl asdjlffsaf水奮斗發的大撒風安德森 發大發大水發", from:1, timestamp: new Date() }, { type:1, message:"做緊d咩嘢?", from:2, timestamp: new Date() }, { type:1, message:"???", from:2, timestamp: new Date() }, ]
然后開始寫vue的代碼
<template> <div class="scroll-wrapper" ref="scroll"> <div class="scroll-content"> <chat-item v-for="item in chatItems" :key="item.message" :type="item.type" :message="item.message" :timestamp="item.timestamp" :from="item.from" ></chat-item> </div> </div> </template> <script> import BScroll from "@better-scroll/core";
import MouseWheel from "@better-scroll/mouse-wheel"
import ChatItem from "./ChatItem";
import { chatItems } from "../../../assets/data/items";
BScroll.use(MouseWheel)
export default {
name: "",
data() {
return {
chatItems,
bs: null
};
},
components: {
"chat-item": ChatItem,
},
mounted() {
this.init();
},
beforeDestroy() {
this.bs.destroy();
},
methods: {
// better-scroll的代碼
init() {
this.bs = new BScroll(this.$refs.scroll, {
scrollY: true, // 上下滾動
click: true, // 開啟點擊事件
startY: document.querySelector(".scroll-wrapper").clientHeight - this.$refs.scroll.scrollHeight + 5 , // 初始高度
mouseWheel: true, // 鼠標滾動
probeType: 2, // listening scroll hook
});
// 下面的不要也行,官網抄的順便留下來了
this.bs.on("scroll", ({ y }) => {
console.log("scrolling:" + y);
});
this.bs.on("scrollEnd", () => {
console.log("scrollingEnd");
});
},
clickHandler(item) {
alert(item);
},
},
}; </script> <style lang="scss" scoped> .scroll-wrapper {
height: calc(100% - 160px); // 留一些空間給 打字的地方 和 header
overflow: hidden; // 非常之關鍵
} </style>
最后是這個樣子的了