前言:给批阅的大佬们敬上
1、项目效果
1.主页
2.城市选择
3.打包上线代码
2、项目实战
1.项目简介
Iconfont 的引入和使用
图片轮播组件的使用
Axios 获取接口数据
组件间数据传递
字母表布局
使用FastClick处理移动端延迟
函数节流与防止性能优化
LocalStorage 缓存选择城市
Vuex 实现城市数据共享
Keep-alive 性能优化
2.使用技术点
Vue + Vue-router + Vue-cli + Axios + Vue-awesome-swiper + Stylus + Flex布局 + ES6 + Eslint + Webpack
3.相关npm依赖包
npm install vue-awesome-swiper@2.6.7 --save
npm install -g stylus
npm install fastclick --save
npm install axios -S
复制代码
3、知识点回顾L
1.使用v-show实现更多按钮的展开收起,transform实现箭头旋转
.arrow1 {
font-size: .24rem;
transform: rotate(180deg);
}
复制代码
2.根据汽车Logo构建多页切换功能
computed: {
pages () {
const pages = []
this.iconsList.forEach((item, index) => {
const page = Math.floor(index / 8)
if (!pages[page]) {
pages[page] = []
}
pages[page].push(item)
})
return pages
}
}
复制代码
3.使用mock数据,开发环境代理
在config文件夹下设置index.js
在module.exports文件中dev的proxyTable设置
proxyTable: {
'/api' : {
target: 'http://localhost:8080' ,
pathRewrite: {
'^/api' : '/static/mock'
}
}
}
复制代码
4.因为只有大中国市级数据,城市选择采用这种展现更合理
上半部分 为 字母指引
下半部分 为 选择字母城市联动
城市数据多的,推荐better-scroll,并更换展现形式
import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/pages/home/Home'
import City from '@/pages/city/City'
Vue.use(Router)
export default new Router({
routes: [{
path: '/' ,
name: 'Home' ,
component: Home
}, {
path: '/city' ,
name: 'City' ,
component: City
}]
})
复制代码
5.使用 Vuex 实现数据共享
建立store文件夹,新建index.js,state 里放置全局公用数据city
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
city: '深圳'
},
mutations: {
changeCity (state, city) {
state.city = city
}
}
})
复制代码
在main.js的根实例下,将store传递进去。
import store from './store' //引入 store
new Vue({
el: '#app' ,
router: router,
store: store, //传递进入根实例的 store
components: { App },
template: '<App/>'
})
复制代码
Vuex的commit方法(触发事件)和Vue-router的push方法(页面跳转)
methods: {
handleCityClick (city) {
this.$store .commit('changeCity' , city)
this.$router .push('/' )
}
}
复制代码
export default new Vuex.Store({
state: {
city: local Storage.city || '深圳'
},
mutations: {
changeCity (state, city) {
state.city = city
local Storage.city = city
}
}
})
复制代码
当用户禁用 localStorage,会致使浏览器报错,建议使用try catch进行优化
let defalutCity = '深圳'
try {
if (local Storage.city) {
defaultCity = local Storage.city
}
} catch (e) {}
export default new Vuex.Store({
state: {
city: defaultCity
},
mutations: {
changeCity (state, city) {
state.city = city
try {
local Storage.city = city
} catch (e) {}
}
}
})
复制代码
6.Keep-alive结合activated生命周期钩子进行Ajax请求的优化
城市不变,汽车资讯不变
7.优化
npm install babel-polyfill --save
复制代码
每次作路由切换时,让新显示的页面回到最顶部。
异步组件拆分,按需加载。
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/' ,
name: 'Home' ,
component: () => import('@/pages/home/Home.vue' )
}, {
path: '/city' ,
name: 'City' ,
component: () => import('@/pages/city/City.vue' )
}
],
scrollBehavior (to, from, savedPosition) {
return { x: 0, y: 0 }
}
})
复制代码
8.打包上线
npm run build
复制代码
3、为前端奋不顾身鸭!
4、预告(下期中级篇更精彩,咱们不见不散哦!)
5、结束语
面试造航母,工做拧螺丝,我将会持续更新。
这是个人微信公众号,欢迎关注!