最近公司要做了一个m站,技术栈为:vuejs2.0全家桶。
下面记录下遇到的一些问题。
1.关于图片懒加载:vue-lazyload
由于项目的图片需要用七牛处理,所以需要定义过滤器。最开始是的思路是v-lazy="list.image_src | urlFilter",通过管道符去使用定义好的过滤器。但是发现不行。最后通过npm官方去查这个组件,发现这个组件有过滤器的配置项,地址:https://www.npmjs.com/package/vue-lazyload
相关代码:
Vue.use(VueLazyload, {
error: 'dist/assets/image_error.png',
loading: 'dist/assets/placeholder6_brand.png',
filter:{
webp ({ src }) {
let imgConfig = "这里是七牛配置"
return src + imgConfig
},
},
try: 3
})
2.使用路由钩子函数设置页面title
const routes = [
{
path: "/",
component: brandSearch,
meta:{title:'选择品牌'}
}
]
const router = new VueRouter({
// mode: 'history',
routes // (缩写)相当于 routes: routes
})
router.afterEach(to =>{document.title = to.meta.title})
3.使用异步组件优化初始化性能
详解地址:http://router.vuejs.org/zh-cn/advanced/lazy-loading.html
将组件定义为异步组件,路由正常去写。
const brandSearch = r => require.ensure([], () => r(require('../component/brand/brandSearch.vue')), 'brandSearch')
这样子在切换到对应路由的时候,才会在页面上插入对应的css和JS文件,避免了随着项目越来越大,初始化性能会大打折扣。
4.vuex在项目中的使用
用在项目中开发非常顺利,例如A页面点击跳转到省市联动组件,在用户选择完省市后返回到A页面,A页面显示用户选择结果。
相关代码:
/**
* 设置省份和城市
*/
setRegion(){
this.$store.commit('setRegion',{"province":this.province,"city":this.city});
this.$router.go(-1)
}
const mutations = {
// mutation 的第一个参数是state
//设置上牌区域
setRegion(state,region){
state.province=region.province+" ";
state.city=region.city;
}
}
action可以提交异步,mutation必须是同步执行。action响应用户事件,mutation是唯一改变state的方式.
5.sass在项目中的使用
在根组件的style中引入全局的样式,这样子我们的单文件组件中就可以随意拿去使用了,需要配置在webpack中配置sass-loader。
<style lang="sass">
@import 'styles/index.scss'
</style>
在单文件组件中 正常去编写样式。
网友评论