[vue] 返回頂部組件(可自定義)

一、大致效果圖

在這裏插入圖片描述
在這裏插入圖片描述
默認: 在這裏插入圖片描述

說明:使用非腳手架開發,腳手架開發使用 ==> 可直接新建.vue文件,複製代碼過去即可。

二、主內容

2.0 頁面調用

<go-top :nav-data="navData" ref="backTop" @handle-click="getHandleClick"></go-top>

2.1 數據獲取

const vm = new Vue({
	el: '#view',
	data() {
		return {
			testData: [],
			navData: []
		}
	},
	created() {
		// 頁面假數據模擬
		for (let i = 0; i < 200; i++) {
			this.testData.push(`testScroll-${i + 1}`)
		}

		// `axios` 獲取導航數據
		axios.get('json/demo-goTop.json').then(res => {
			this.navData = res.data.navData
		}).catch(err => {
			console.log(err)
		})
	},
	methods: {
		// 獲取子組件點擊事件傳的值
		getHandleClick(data, index, event) {
			switch (data.clickType) {
				case 0:
					return false
				case 1:
					window.open(data.urlPath)
					break
				case 2:
					window.open(data.urlPath, '_blank',
						'width=300,height=300,menubar=no,toolbar=no, status=no,scrollbars=yes')
					break
				case 3:
					this.$refs.backTop.goTopClick()
					break
			}
		}
	}
})

2.2 組件

Vue.component('go-top', {
	template: `
		<div class="top-warp" v-if="navData.length">
			<div class="top-ul">
				<div class="top-li" v-for="(val,key) in navData" :key="key" v-if="val.isShowTop" :style="bgStyle(key, oneNavHover)"
				@click="handleClickData(val, key, $event)" @mouseover="addHoverStyle(key)" @mouseleave="cleanHoverStyle">
					<i class="iconfont" :class="val.icon"></i>
					<div class="top-li-msg" :class="{'top-QR' : val.children.length}" :style="bgStyle(key, twoNavHover)">
						<span class="top-triangle" :style="brColor(key, twoNavHover)"></span>
						<span v-if="!val.children.length">{{val.title}}</span>
						<div class="top-img-flex" v-else>
							<div class="top-img" v-for="(v,k) in val.children" :key="k">
								<img :src="v.imgPath">
								<span>{{v.msg}}</span>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	`,
	props: {
		navData: {
			type: Array,
			default: () => []
		},
		speed: {
			type: Number,
			default: 100
		},
		showBtnOffset: {
			type: Number,
			default: 200
		},
		oneNavHover: {
			type: String,
			default: '#000000'
		},
		twoNavHover: {
			type: String,
			default: '#f44444'
		}
	},
	data() {
		return {
			hoverIndex: null
		}
	},
	mounted() {
		window.addEventListener('scroll', this.getScollTop, true)
	},
	methods: {
		// 動態添加樣式
		bgStyle(key, hoverStyle) {
			return {
				background: key == this.hoverIndex ? hoverStyle : ''
			}
		},
		brColor(key, hoverStyle) {
			return {
				borderLeftColor: key == this.hoverIndex ? hoverStyle : ''
			}
		},
		addHoverStyle(index) {
			this.hoverIndex = index
		},
		cleanHoverStyle() {
			this.hoverIndex = null
		},

		// 當前點擊
		handleClickData(data, index, event) {
			this.$emit('handle-click', data, index, event)
		},

		// 滾動條
		getScollTop() {
			let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
			this.navData.filter(item => {
				if (scrollTop > this.showBtnOffset) {
					return item.clickType == 3 ? item.isShowTop = true : item.isShowTop = true
				} else {
					return item.clickType == 3 ? item.isShowTop = false : item.isShowTop = true
				}
			})
		},

		// 返回頂部點擊
		goTopClick() {
			let cleanTime = setInterval(() => {
				document.documentElement.scrollTop -= this.speed
				if (document.documentElement.scrollTop === 0) {
					this.cleanHoverStyle()
					clearInterval(cleanTime)
				}
			}, 10)
		}
	}
})

2.31 Attributes

參數 類型 默認值 說明
nav-data Array [] 導航數據(即下面的json
speed Number 100 滾動條滾動到頂部的速度
show-btn-offset Number 200 返回頂部按鈕出現的初始位置
one-nav-hover String ‘#000000’ 一級導航鼠標經過背景顏色
two-nav-hover String ‘#f44444’ 二級導航背景顏色
backTop String ref="backTop" *想要返回頂部功能,此項必須加上

2.32 Events

事件名 參數 說明
handle-click data, index, event 當前項導航點擊時,獲取子組件的數據,下標及 event。通過 data.clickType 判斷點擊之後,具體要做什麼,返回頂部按鈕點擊時,需要手動觸發方法:this.$refs.backTop.goTopClick()

2.4 json 數據格式

{
	"navData": [{
			"icon": "icon-fanhuidingbu",
			"urlPath": "https://www.csdn.net/",
			"title": "返回頂部",
			"isShowTop": false,
			"clickType": 3,
			"children": []
		},
		{
			"icon": "icon-erweima",
			"urlPath": "https://www.csdn.net/",
			"title": "",
			"clickType": 0,
			"isShowTop": true,
			"children": [{
					"msg": "關注公衆號",
					"imgPath": "https://g.csdnimg.cn/side-toolbar/1.2/images/qr_wechat.png"
				},
				{
					"msg": "下載APP",
					"imgPath": "https://g.csdnimg.cn/side-toolbar/1.2/images/qr_app.png"
				}
			]
		},
		{
			"icon": "icon-2zaixiankefucheng",
			"urlPath": "https://www.csdn.net/",
			"title": "在線客服",
			"clickType": 1,
			"isShowTop": true,
			"children": []
		},
		{
			"icon": "icon-fankuiyijian",
			"urlPath": "https://www.csdn.net/",
			"title": "意見反饋",
			"clickType": 2,
			"isShowTop": true,
			"children": []
		}
	]
}
三、全部html
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>vue返回頂部組件</title>
		<link rel="stylesheet" type="text/css" href="//at.alicdn.com/t/font_1078306_8ycnernwlnu.css" />
		<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
		<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
		<style type="text/css">
			* {
				margin: 0;
				padding: 0;
				box-sizing: border-box;
			}

			html,
			body,
			section {
				width: 100%;
				height: 100%;
				background: #F5F5F5;
			}

			[v-clock] {
				display: none;
			}

			/* start */
			.top-warp {
				width: 38px;
				min-height: 38px;
				position: fixed;
				right: 20px;
				bottom: 60px;
				cursor: pointer;
				background: white;
				box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
			}

			.top-ul {
				display: flex;
				flex-direction: column;
			}

			.top-li {
				width: 100%;
				height: 38px;
				display: flex;
				position: relative;
			}

			.top-li i {
				margin: auto;
			}

			.top-li-msg {
				position: absolute;
				height: 38px;
				line-height: 38px;
				left: -100px;
				width: 74px;
				color: white;
				font-size: 14px;
				text-align: center;
				transition: left .5s ease;
				transform-style: preserve-3d;
				visibility: hidden;
				opacity: 0;
			}

			.top-triangle {
				position: absolute;
				right: -5px;
				top: 50%;
				transform: translateY(-50%);
				width: 0;
				height: 0;
				border-style: solid;
				border-width: 5px 0 5px 5px;
				border-color: transparent transparent transparent #f44444;
			}

			.top-QR {
				height: 125px;
				width: 200px;
				top: 50%;
				left: -226px;
				transform: translateY(-50%);
				z-index: 1;
				display: flex;
			}

			.top-nav {
				background: #f44444;
			}

			.top-img-flex {
				display: flex;
				width: 100%;
			}

			.top-img {
				flex: 1;
				padding: 10px;
				font-size: 14px;
				display: flex;
				flex-direction: column;
				margin: auto;
			}

			.top-img img {
				width: 80px;
				height: 80px;
				margin: auto;
			}

			.top-li:hover {
				color: white;
			}

			.top-li:hover .top-li-msg {
				left: -74px;
				transition: left .5s ease;
				visibility: visible;
				opacity: 1;
			}

			.top-li:hover .top-QR {
				left: -200px;
			}

			/* end */
		</style>
	</head>
	<body>
		<section id="view" clock>
			<div v-for="v in testData" :key="v">{{v}}</div>
			<go-top :nav-data="navData" :speed="300" one-nav-hover="#09F" two-nav-hover="green" @handle-click="getHandleClick"
			 :show-btn-offset="1000" ref="backTop"></go-top>
		</section>
	</body>

	<script type="text/javascript">
		Vue.component('go-top', {
			template: `
				<div class="top-warp" v-if="navData.length">
					<div class="top-ul">
						<div class="top-li" v-for="(val,key) in navData" :key="key" v-if="val.isShowTop" :style="bgStyle(key, oneNavHover)"
						@click="handleClickData(val, key, $event)" @mouseover="addHoverStyle(key)" @mouseleave="cleanHoverStyle">
							<i class="iconfont" :class="val.icon"></i>
							<div class="top-li-msg" :class="{'top-QR' : val.children.length}" :style="bgStyle(key, twoNavHover)">
								<span class="top-triangle" :style="brColor(key, twoNavHover)"></span>
								<span v-if="!val.children.length">{{val.title}}</span>
								<div class="top-img-flex" v-else>
									<div class="top-img" v-for="(v,k) in val.children" :key="k">
										<img :src="v.imgPath">
										<span>{{v.msg}}</span>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			`,
			props: {
				navData: {
					type: Array,
					default: () => []
				},
				speed: {
					type: Number,
					default: 100
				},
				showBtnOffset: {
					type: Number,
					default: 200
				},
				oneNavHover: {
					type: String,
					default: '#000000'
				},
				twoNavHover: {
					type: String,
					default: '#f44444'
				}
			},
			data() {
				return {
					hoverIndex: null
				}
			},
			mounted() {
				window.addEventListener('scroll', this.getScollTop, true)
			},
			methods: {
				// 動態添加樣式
				bgStyle(key, hoverStyle) {
					return {
						background: key == this.hoverIndex ? hoverStyle : ''
					}
				},
				brColor(key, hoverStyle) {
					return {
						borderLeftColor: key == this.hoverIndex ? hoverStyle : ''
					}
				},
				addHoverStyle(index) {
					this.hoverIndex = index
				},
				cleanHoverStyle() {
					this.hoverIndex = null
				},

				// 當前點擊
				handleClickData(data, index, event) {
					this.$emit('handle-click', data, index, event)
				},

				// 滾動條
				getScollTop() {
					let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
					this.navData.filter(item => {
						if (scrollTop > this.showBtnOffset) {
							return item.clickType == 3 ? item.isShowTop = true : item.isShowTop = true
						} else {
							return item.clickType == 3 ? item.isShowTop = false : item.isShowTop = true
						}
					})
				},

				// 返回頂部點擊
				goTopClick() {
					let cleanTime = setInterval(() => {
						document.documentElement.scrollTop -= this.speed
						if (document.documentElement.scrollTop === 0) {
							this.cleanHoverStyle()
							clearInterval(cleanTime)
						}
					}, 10)
				}
			}
		})
	</script>

	<script type="text/javascript">
		const vm = new Vue({
			el: '#view',
			data() {
				return {
					testData: [],
					navData: []
				}
			},
			created() {
				// 頁面假數據模擬
				for (let i = 0; i < 200; i++) {
					this.testData.push(`testScroll-${i + 1}`)
				}

				// `axios` 獲取導航數據
				axios.get('json/demo-goTop.json').then(res => {
					this.navData = res.data.navData
				}).catch(err => {
					console.log(err)
				})
			},
			methods: {
				// 獲取子組件點擊事件傳的值
				getHandleClick(data, index, event) {
					switch (data.clickType) {
						case 0:
							return false
						case 1:
							window.open(data.urlPath)
							break
						case 2:
							window.open(data.urlPath, '_blank',
								'width=300,height=300,menubar=no,toolbar=no, status=no,scrollbars=yes')
							break
						case 3:
							this.$refs.backTop.goTopClick()
							break
					}
				}
			}
		})
	</script>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章