vue吸顶和平滑效果及其他问题记录
2020-03-02 本文已影响0人
北风吹_yfy
一、导航条吸顶效果
需求:官网内部有个水平导航条,当向下滑动到导航条置顶时需要固定在顶部。
实现方法:
<template>
<header ref="boxFixed" :class="{'is_fixed' : isFixed}">
<section class="header-box">
<img src="./src/logo2.png" alt="">
<nav>
<ul>
<li>首页</li>
<li>产品介绍</li>
<li>APP下载</li>
<li>免费注册使用</li>
</ul>
</nav>
</section>
</header>
</template>
<script>
export default {
data(){
return {
isFixed: false,
offsetTop:0
}
},
mounted(){
window.addEventListener('scroll',this.handleScroll);
this.$nextTick( () => {
this.offsetTop = this.$refs.boxFixed.offsetTop;
})
},
methods:{
handleScroll() {
let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
this.isFixed = scrollTop > this.offsetTop ? true : false;
},
},
destroyed () {
window.removeEventListener('scroll', this.handleScroll)
},
}
</script>
<style>
.isFixed {
position:fixed;
top:0;
left:0;
z-index:2;
}
</style>
二、平滑效果
需求:在切换导航tab时需要将页面平滑置顶到初始位置。
实现方法:
// 切换tab
handleTab (index) {
this.currentIndex = index
window.scrollTo({
top: 0,
behavior: 'smooth'
})
},
- scrollTo有两种语法:
// 1.scrollTo(x,y) //指定滚动到x轴和y轴的位置
// 2.scrollTo(options) //options有三个参数,(left,top,behavior ),
// top 等同于 y-coord
// left 等同于 x-coord
// behavior 类型String,表示滚动行为,支持参数 smooth(平滑滚动),instant(瞬间滚动),默认值auto,实测效果等同于instant
window.scrollTo({
top: 0,
behavior: "smooth"
});
三、去掉vue路由地址中的#/以及重定向
需求:去掉vue路由地址中的#/,问题是部署之后页面无法显示
实现方法:利用路由重定向
// router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import Index from '@/views/index.vue'
Vue.use(Router)
export default new Router({
base: '/conferenceportal', // 设置base属性
mode: 'history', // 去掉#号
routes: [
{
path: '/',
name: 'index',
component: Index
}
]
})
// App.vue
<script>
export default {
name: 'App',
created () {
this.$router.push('/') // 重定向到首页
}
}
四、解决vue中锚点问题
需求:点击侧边导航栏是要跳到对应的内容区
实现方法:如果使用a标签的href属性结合id可以实现功能,但是会出现页面路由被改变的问题,所以此处使用click事件结合scrollIntoView事件解决问题:
<ul class="slide" v-show="index===0">
<li v-for="(item,index) in slideList" :key="index" :class="{checkedslide: slideIndex === index}" @click="handleSlide(index)">
{{ item }}
</li>
</ul>
<div class="card">
<p class="title" ref="one">Rmeet会议</p>
.....
</div>
<div class="card">
<p class="title" ref="two">视频会议室</p>
.....
</div>
<div class="card">
<p class="title" ref="three">融合会议</p>
.....
</div>
export default {
data () {
return {
slideIndex: 0,
slideList: ['Rmeet会议', '视频会议室', '融合会议']
}
},
methods: {
// 切换侧边栏
handleSlide (index) {
this.slideIndex = index
if (index === 0) {
this.$refs.one.scrollIntoView(true)
}
if (index === 1) {
this.$refs.two.scrollIntoView(true)
}
if (index === 2) {
this.$refs.three.scrollIntoView(true)
}
}
}
五、vue移动端实现拨号功能(点击手机号就拨号)
- 在vue项目的index.html中添加如下代码:
<meta name="format-detection" content="telephone=yes" />
- 在需要调起手机拨号功能的页面,写如下方法:
callPhone (phoneNumber) {
window.location.href = 'tel://' + phoneNumber
}
- 在拨号的页面调用此方法:
// Phone是请求得到的数据
<span @click="callPhone(Phone)">{{ Phone }}</span>