做一个Header切换组件,并实现吸顶效果
1.先做一个Header组件
//===>src/views/Film/FilmHeader.vue
<template>
<div>
<ul>
<router-link to="/film/nowplaying" tag="li" activeClass="active">正在热映</router-link>
<router-link to="/film/comingsoon" tag="li" activeClass="active">即将上演</router-link>
</ul>
</div>
</template>
<style lang="scss" scoped>
ul {
display: flex;
li {
flex: 1;
height: 40px;
line-height: 40px;
text-align: center;
background: white;
}
}
.active {
color: red;
border-bottom: 2px solid red;
}
</style>
2.在Film页面导入FilmHeader
//===>src/views/Film.vue
<template>
<div>
<swiper :key="looplist.length">
<div class="swiper-slide" v-for="data in looplist" :key="data">
<img :src="data" />
</div>
</swiper>
<filmheader></filmheader>
<router-view></router-view>
</div>
</template>
<script>
import swiper from "@/views/Film/Swiper";
import filmheader from "@/views/Film/FilmHeader";
import axios from "axios";
export default {
data() {
...
},
components: {
swiper,
filmheader
},
mounted() {
...
}
};
</script>
...
效果
现在,我们想实现顶部悬停效果,即上拉页面时,FilmHeader组件滑到顶部会停在那里
3.修改Film页面,通过window.onscroll获取FilmHeader的滚动位置,使用:class语法动态控制悬停属性
//===>src/views/Film.vue
<template>
<div>
<swiper :key="looplist.length" ref="myswiper">
<div class="swiper-slide" v-for="data in looplist" :key="data">
<img :src="data" />
</div>
</swiper>
<filmheader :class="isFix?'fixed':''"></filmheader>
<router-view></router-view>
</div>
</template>
<script>
import swiper from "@/views/Film/Swiper";
import filmheader from "@/views/Film/FilmHeader";
import axios from "axios";
export default {
data() {
return {
looplist: [],
isFix: false
};
},
components: {
swiper,
filmheader
},
mounted() {
axios({
url: "https://m.maizuo.com/gateway?filmId=4837&k=9593174",
headers: {
"X-Client-Info":
'{"a":"3000","ch":"1002","v":"5.0.4","e":"159065562332628866547713"}',
"X-Host": "mall.film-ticket.film.info"
}
}).then(res => {
console.log(res.data);
this.looplist = res.data.data.film.photos;
});
window.onscroll = this.handleScroll;
},
methods: {
handleScroll() {
if (
document.documentElement.scrollTop >=
this.$refs.myswiper.$el.offsetHeight
) {
this.isFix = true;
} else {
this.isFix = false;
}
}
}
};
</script>
<style lang="sass" scoped>
</style>
4.在FilmHeader文件中,编写fixed悬停的属性
//===>src/views/Film/FilmHeader.vue
<template>
...
</template>
<style lang="scss" scoped>
...
.fixed {
position: fixed;
left: 0px;
top: 0px;
width: 100%;
height: 40px;
background: white;
}
</style>
至此悬停功能完成了。
效果
疫情期间,电影院电影太少,以至于我不能上拉页面去测试悬停效果,所以,我把复制一点假数据模拟一下。
5*.修改Nowplaying.vue组件,向datalist添加模拟数据
//===>src/views/Film/Nowplaying.vue
<template>
...
</template>
<script>
...
export default {
data() {
return {
datalist: []
};
},
mounted() {
...
axios({
...
}).then(res => {
console.log(res.data);
this.datalist = res.data.data.films;
console.log(...this.datalist);
this.datalist = [
...this.datalist,
...this.datalist,
...this.datalist,
...this.datalist,
...this.datalist
];
});
},
...
</script>
<style lang="scss" scoped>
...
</style>
效果实现了
因为报错了,我们测试看到效果,就可以把刚添加的重复数据删掉了
网友评论