项目架构
项目目录
├── build
├── config
├── dist
│ └── static
│ ├── css
│ ├── fonts
│ ├── images
│ ├── js
│ └── lib
├── src
│ ├── api
│ ├── assets
│ │ ├── global
│ │ └── images
│ │ └── footer
│ ├── components
│ │ ├── common
│ │ ├── news
│ │ └── profile
│ │ └── charge
│ ├── config
│ ├── mixin
│ ├── router
│ ├── service
│ ├── store
│ └── util
└── static
├── images
└── lib
项目目录是采用
vue-cli
自动生成,其它按需自己新建就好了。
开发实践
动态修改 document title
在不同的路由页面,我们需要动态的修改文档标题,可以将每个页面的标题配置在路由元信息
meta
里面带上,然后在
router.beforeEach
钩子函数中修改:
import Vue from 'vue';
import Router from 'vue-router';
Vue.use(Router);
const router = new Router({
mode: 'history',
routes: [
{ path: '/', component: Index, meta: { title: '推荐产品得丰厚奖金' } },
{
path: '/news',
component:
News,
meta: { title: '公告列表' },
children: [
{ path: '', redirect: 'list' },
{ path: 'list', component: NewsList },
{ path: 'detail/:newsId', component: NewsDetail, meta: { title: '公告详情' } }
]
},
{
path: '/guide',
component: GuideProtocol,
meta: {
title: '新手指南'
}
}
]
});
router.beforeEach((to, from, next) => {
let documentTitle = '商城会员平台';
// path 是多级的,遍历
to.matched.forEach((path) => {
if (path.meta.title) {
documentTitle += ` - ${path.meta.title}`;
}
});
document.title = documentTitle;
next();
});
Event Bus 使用场景
我们在项目中引入了
vuex
,通常情况下是不需要使用
eventbus
的,但是有一种情况下我们需要使用它,那就是在路由钩子函数内部的时,在项目中,我们需要在
beforeEnter
路由钩子里面对外抛出事件,在这个钩子函数中我们无法去到
this
对象。
beforeEnter: (to, from, next) => {
const userInfo = localStorage.getItem(userFlag);
if
(isPrivateMode()) {
EventBus.$emit('get-localdata-error');
next(false);
return;
}
})
在
App.vue
的
mouted
方法中监听这个事件
EventBus.$on('get-localdata-error', () => {
this.$alert('请勿使用无痕模式浏览');
});
自定义指令实现埋点数据统计
在项目中通常需要做数据埋点,这个时候,使用自定义指令将会变非常简单
在项目入口文件
main.js
中配置我们的自定义指令
// 坑位埋点指令
Vue.directive('stat', {
bind(el, binding) {
el.addEventListener('click', () => {
const data = binding.value;
let prefix = 'store';
if (OS.isAndroid || OS.isPhone) {
prefix = 'mall';
}
analytics.request({
ty: `${prefix}_${data.type}`,
dc: data.desc || ''
}, 'n');
}, false);
}
});
在组件中使用我们的自定义指令
使用过滤器实现展示信息格式化
如下图中奖金数据信息,我们需要将后台返回的奖金格式化为带两位小数点的格式,同时,如果返回的金额是区间类型,需要额外加上
起
字和
¥
金额符号
在入口文件
main.js
中配置我们自定义的过滤器
Vue.filter('money', (value, config = { unit: '¥', fixed: 2 }) => {
const moneyStr = `${value}`;
if (moneyStr.indexOf('-') > -1) {
const scope = moneyStr.split('-');
return `${config.unit}${parseFloat(scope[0]).toFixed(config.fixed).toString()} 起`;
} else if (value === 0) {
return value;
}
return
`${config.unit}${parseFloat(moneyStr).toFixed(config.fixed).toString()}`;
});
在组件中使用:
class="price">{{detail.priceScope | money}}
:class="{singleWrapper: isMobile}">
class="rate">比率:{{detail.commissionRateScope}}%
class="income">奖金:{{detail.expectedIncome | money}}