组件优化
从整个项目来看,还需要优化的地方就是Header组件,因为项目中Header组件在App.vue中是单独的一个,Detail.vue中是单独的一个,Account.vue中又是单独的一个,虽然这三个Header都可以实现同步控制VueX中的主题状态,但是没有达到组件复用性。


他们都有一个公共的左中右结构,并且都可以实现点击换肤功能,所以可以将这一特性抽离出来,封装为一个公共的组件。不同的地方使用具名插槽的思想来替换其中的内容。
<!-- Header.vue --><template><div class="header" @click="changeTheme"><!-- 注意点:不能直接设置插槽的样式 --><div class="header-left"><slot name="left">左边</slot></div><slot name="center" class="">中间</slot><div class="header-right"><slot name="right">右边</slot></div></div></template><script>import { mapActions } from 'vuex'export default {name: 'Header',methods: {...mapActions(['setTheme']),changeTheme () {// 循环主题索引this.setTheme()}}}</script><style scoped lang="scss">@import "../assets/css/variable";@import "../assets/css/mixin";.header{width: 100%;height: 100px;@include bg_color();display: flex;justify-content: space-between;align-items: center;padding: 0 20px;.header-left,.header-right{width: 84px;height: 84px;text-align: center;line-height: 84px;}}</style>
其他界面中使用:
<!-- App.vue --><template><Header class="header"><div slot="left" class="header-left"><i :class="['iconfont', curThemeIcon]" ref="headericon"></i></div><p slot="center" class="header-title">南先生的网易云</p><div slot="right" class="header-right" @click.stop="accountClick"><i class="iconfont icon-yonghu"></i></div></Header></template>
缓存特定组件
在整个项目中,网络请求量最大的就是歌手页,但是歌手页的数据一经获取之后其实不会有太多变动的地方,所以可以将此组件缓存起来,下一次切换到该组件就不会重新获取数据了,减轻了服务器的压力。还有搜索界面其实也是基本固定的,所以可以将这两个组件一同缓存起来。方法很简单,可以利用keep-alive对特定组件进行缓存。详细可参考官网
<template><div id="app"><MainHeader></MainHeader><Tabbar></Tabbar><keep-alive include="Singer, Search"><router-view></router-view></keep-alive><Player></Player></div></template>
