1.关于全局过滤器的注册
抽出到文件,然后使用 Object.keys 在 main.js 入口统一注册:
/src/common/filters.js
let dateServer = value => value.replace(/(\d{4})(\d{2})(\d{2})/g, '$1-$2-$3')
export { dateServer }
/src/main.js
import * as custom from './common/filters/custom'
Object.keys(custom).forEach(key => Vue.filter(key, custom[key]))
然后在其他.vue文件中就可以使用了。
2. 全局组件注册
避免每次通过import导入
/src/components/ componentRegister .js
import Vue from 'vue'
/**
* 首字母大写
* @param str 字符串
* @example heheHaha
* @return {string} HeheHaha
*/
function capitalizeFirstLetter(str) {
return str.charAt(0).toUpperCase() + str.slice(1)
}
/**
* 对符合'xx/xx.vue'组件格式的组件取组件名
* @param str fileName
* @example abc/bcd/def/basicTable.vue
* @return {string} BasicTable
*/
function validateFileName(str) {
return /^\S+\.vue$/.test(str) &&
str.replace(/^\S+\/(\w+)\.vue$/, (rs, $1) => capitalizeFirstLetter($1))
}
const requireComponent = require.context('./', true, /\.vue$/)
// 找到组件文件夹下以.vue命名的文件,如果文件名为index,那么取组件中的name作为注册的组件名
requireComponent.keys().forEach(filePath => {
const componentConfig = requireComponent(filePath)
const fileName = validateFileName(filePath)
const componentName = fileName.toLowerCase() === 'index'
? capitalizeFirstLetter(componentConfig.default.name)
: fileName
Vue.component(componentName, componentConfig.default || componentConfig)
})
只需在main.js中import "components/componentRegister.js",这样就可以随时使用这些基础组件
3. 不同路由的组件复用
3.1 场景还原
当某个场景中 vue-router从/post-page/a,跳转到 /post-page/b。然后我们惊人地发现,页面跳转后数据竟然没更新?!原因是 vue-router "智能地"发现这是同一个组件,然后它就决定要复用这个组件,所以你在 created 函数里写的方法压根就没执行。通常的解决方案是监听 $route 的变化来初始化数据,如下:
data() {
return {
loading: false,
error: null,
post: null
}
},
watch: {
'$route': { // 使用watch来监控是否是同一个路由
handler: 'resetData',
immediate: true
}
},
methods: {
resetData() {
this.loading = false
this.error = null
this.post = null
this.getPost(this.$route.params.id)
},
getPost(id){ }
}
3.2 优化
为了实现这样的效果可以给 router-view添加一个不同的 key,这样即使是公用组件,只要 url 变化了,就一定会重新创建这个组件。
<router-view :key="$route.fullpath"></router-view>
还可以在其后加 ++newDate()时间戳,保证独一无二。
如果组件被放在 <keep-alive>中的话,可以把获取新数据的方法放在 activated 钩子,代替原来在 created、mounted 钩子中获取数据的任务。
4.路由根据开发状态懒加载
一般情况
一般我们在路由中加载组件的时候:
import Login from '@/views/login.vue'
export default new Router({
routes: [{ path: '/login', name: '登陆', component: Login}]
})
当你需要懒加载 lazy-loading 的时候,需要一个个把 routes 的 component 改为 ()=>import('@/views/login.vue'),甚为麻烦。
当你的项目页面越来越多之后,在开发环境之中使用 lazy-loading 会变得不太合适,每次更改代码触发热更新都会变得非常的慢。所以建议只在生成环境之中使用路由懒加载功能。
在生成环境中使用路由懒加载功能
根据Vue的一部组件和Webpack的代码分割功能实现组件的懒加载,如:
const Foo = () => import('./Foo.vue')
在区分开发环境与生产环境时,可以在路由文件夹下分别新建两个文件:
_import_production.js
module.exports = file => () => import('@/views/' + file + '.vue')
_import_development.js (这种写法 vue-loader版本至少v13.0.0以上)
module.exports = file => require('@/views/' + file + '.vue').default
而在设置路由的 router/index.js文件中或者其他路由分块中去调用:
const _import = require('./_import_' + process.env.NODE_ENV)
export default new Router({
routes: [{ path: '/login', name: '登陆', component: _import('login/index') }]
})