在vue的使用过程当中会遇到各类场景,当普通使用时以为没什么,可是或许优化一下能够更高效更优美的进行开发。下面有一些我在平常开发的时候用到的小技巧,在下将不按期更新~javascript
有时候咱们会遇到这样的场景,一个组件中有几个图表,在浏览器resize的时候咱们但愿图表也进行resize,所以咱们会在父容器组件中写:html
mounted() {
setTimeout(() =>window.onresize = () => {
this.$refs.chart1.chartWrapperDom.resize()
this.$refs.chart2.chartWrapperDom.resize()
// ...
}, 200)
destroyed() { window.onresize = null }
复制代码
这样子图表组件若是跟父容器组件不在一个页面,子组件的状态就被放到父组件进行管理,为了维护方便,咱们天然但愿子组件的事件和状态由本身来维护,这样在添加删除组件的时候就不须要去父组件挨个修改vue
这里使用了lodash的节流throttle函数,也能够本身实现,这篇文章也有节流的实现能够参考一下。 以Echarts为例,在每一个图表组件中:java
computed: {
/**
* 图表DOM
*/
chartWrapperDom() {
const dom = document.getElementById('consume-analy-chart-wrapper')
return dom && Echarts.init(dom)
},
/**
* 图表resize节流,这里使用了lodash,也能够本身使用setTimout实现节流
*/
chartResize() {
return _.throttle(() =>this.chartWrapperDom && this.chartWrapperDom.resize(), 400)
}
},
mounted() {
window.addEventListener('resize', this.chartResize)
},
destroyed() {
window.removeEventListener('resize', this.chartResize)
}
复制代码
官方注册过滤器的方式:webpack
exportdefault {
data () { return {} },
filters:{
orderBy (){
// doSomething
},
uppercase () {
// doSomething
}
}
}
复制代码
可是咱们作项目来讲,大部分的过滤器是要全局使用的,不会往往用到就在组件里面去写,抽成全局的会更好些。 官方注册全局的方式:git
// 注册
Vue.filter('my-filter', function (value) {
// 返回处理后的值
})
// getter,返回已注册的过滤器var myFilter = Vue.filter('my-filter')
复制代码
可是分散写的话不美观,所以能够抽出成单独文件。github
咱们能够抽出到独立文件,而后使用Object.keys在main.js入口统一注册web
/src/common/filters.js正则表达式
let dateServer = value => value.replace(/(\d{4})(\d{2})(\d{2})/g, '$1-$2-$3')
export { dateServer }
复制代码
/src/main.jsvue-router
import * as custom from'./common/filters/custom'Object.keys(custom).forEach(key => Vue.filter(key, custom[key]))
复制代码
而后在其余的.vue 文件中就可愉快地使用这些咱们定义好的全局过滤器了
<template><sectionclass="content"><p>{{ time | dateServer }}</p><!-- 2016-01-01 --></section></template><script>exportdefault {
data () {
return {
time: 20160101
}
}
}
</script>
复制代码
须要使用组件的场景:
<template><BaseInputv-model="searchText" @keydown.enter="search"/><BaseButton @click="search"><BaseIconname="search"/></BaseButton></template><script>import BaseButton from'./baseButton'import BaseIcon from'./baseIcon'import BaseInput from'./baseInput'exportdefault {
components: { BaseButton, BaseIcon, BaseInput }
}
</script>
复制代码
咱们写了一堆基础UI组件,而后每次咱们须要使用这些组件的时候,都得先import,而后声明components,很繁琐,这里可使用统一注册的形式
咱们须要借助一下神器webpack,使用 require.context()
方法来建立本身的模块上下文,从而实现自动动态require组件。这个方法须要3个参数:要搜索的文件夹目录、是否还应该搜索它的子目录、以及一个匹配文件的正则表达式。 咱们在components文件夹添加一个叫componentRegister.js的文件,在这个文件里借助webpack动态将须要的基础组件通通打包进来。
/src/components/componentRegister.js
import Vue from'vue'/**
* 首字母大写
* @param str 字符串
* @example heheHaha
* @return {string} HeheHaha
*/functioncapitalizeFirstLetter(str) {
return str.charAt(0).toUpperCase() + str.slice(1)
}
/**
* 对符合'xx/xx.vue'组件格式的组件取组件名
* @param str fileName
* @example abc/bcd/def/basicTable.vue
* @return {string} BasicTable
*/functionvalidateFileName(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)
})
复制代码
这里文件夹结构:
components
│ componentRegister.js
├─BasicTable
│ BasicTable.vue
├─MultiCondition
│ index.vue
复制代码
这里对组件名作了判断,若是是index的话就取组件中的name属性处理后做为注册组件名,因此最后注册的组件为:multi-condition
、basic-table
最后咱们在main.js中import 'components/componentRegister.js',而后咱们就能够随时随地使用这些基础组件,无需手动引入了~
当某个场景中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 = falsethis.error = nullthis.post = nullthis.getPost(this.$route.params.id)
},
getPost(id){ }
}
复制代码
那要怎么样才能实现这样的效果呢,答案是给router-view
添加一个不一样的key,这样即便是公用组件,只要url变化了,就必定会从新建立这个组件。
<router-view:key="$route.fullpath"></router-view>
复制代码
还能够在其后加+ +new Date()
时间戳,保证独一无二
// 父组件
<BaseInput:value="value"label="密码"placeholder="请填写密码"
@input="handleInput"
@focus="handleFocus"></BaseInput>
// 子组件
<template><label>
{{ label }}
<input:value=" value":placeholder="placeholder"
@focus="$emit('focus', $event)"
@input="$emit('input', $event.target.value)"></label></template>
复制代码
vue的组件实例中的$props
、$attrs
给咱们提供了很大的便利,特别是父子组件传值的时候。
一、 每个从父组件传到子组件的props,咱们都得在子组件的Props中显式的声明才能使用。这样一来,咱们的子组件每次都须要申明一大堆props,这里咱们知道v-bind 是能够传对象的,能够在 vm.$props
中拿到全部父组件props的值 v-bind="$props"
<inputv-bind="$props"
@input="$emit('input', $event.target.value)">
复制代码
二、 相似placeholer这种dom原生的property可使用$attrs
直接从父传到子,无需声明。方法以下:
<input:value="value"v-bind="$attrs"
@input="$emit('input', $event.target.value)">
复制代码
$attrs
包含了父做用域中不做为 prop 被识别 (且获取) 的特性绑定 (class 和 style 除外)。当一个组件没有声明任何 prop 时,这里会包含全部父做用域的绑定,而且能够经过 v-bind="$attrs"
传入内部组件。
三、 注意到子组件的@focus="$emit('focus', $event)"
其实什么都没作,只是把event传回给父组件而已,那其实和上面相似,彻底不必显式地申明:
<input :value="value"
v-bind="$attrs"
v-on="listeners"/>
computed: {
listeners() {
return {
...this.$listeners,
input: event =>this.$emit('input', event.target.value)
}
}
}
复制代码
$listeners
包含了父做用域中的 (不含 .native 修饰器的) v-on 事件监听器。它能够经过 v-on="$listeners"
传入内部组件——在建立更高层次的组件时很是有用。
须要注意的是,因为咱们input并非BaseInput这个组件的根节点,而默认状况下父做用域的不被认做 props
的特性绑定将会“回退”且做为普通的 HTML 特性应用在子组件的根元素上。因此咱们须要设置 inheritAttrs: false
,这些默认行为将会被去掉,上面优化才能成功。
通常咱们在路由中加载组件的时候:
import Login from'@/views/login.vue'exportdefaultnew 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)
exportdefaultnew Router({
routes: [{ path: '/login', name: '登录', component: _import('login/index') }]
})
复制代码
这样组件在开发环境下就是非懒加载,生产环境下就是懒加载的了
vue-loader 是处理 *.vue 文件的 webpack loader。它自己提供了丰富的 API,有些 API 很实用但不多被人熟知。例如接下来要介绍的 preserveWhitespace
和 transformToRequire
preserveWhitespace
减小文件体积有些时候咱们在写模板时不想让元素和元素之间有空格,可能会写成这样:
<ul><li>1111</li><li>2222</li><li>333</li></ul>
复制代码
固然还有其余方式,好比设置字体的font-size: 0
,而后给须要的内容单独设置字体大小,目的是为了去掉元素间的空格。其实咱们彻底能够经过配置 vue-loader 实现这一需求。
{
vue: {
preserveWhitespace: false
}
}
复制代码
它的做用是阻止元素间生成空白内容,在 Vue 模板编译后使用 _v(" ")
表示。若是项目中模板内容多的话,它们仍是会占用一些文件体积的。例如 Element 配置该属性后,未压缩状况下文件体积减小了近 30Kb。
transformToRequire
不再用把图片写成变量了之前在写 Vue 的时候常常会写到这样的代码:把图片提早 require 传给一个变量再传给组件。
<template><div><avatar:default-src="DEFAULT_AVATAR"></avatar></div></template><script>exportdefault {
created () {
this.DEFAULT_AVATAR = require('./assets/default-avatar.png')
}
}
</script>
复制代码
其实经过配置 transformToRequire
后,就能够直接配置,这样vue-loader会把对应的属性自动 require 以后传给组件
{
vue: {
transformToRequire: {
avatar: ['default-src']
}
}
}
复制代码
因而咱们代码就能够简化很多
<template><div><avatardefault-src="./assets/default-avatar.png"></avatar></div></template>
复制代码
在 vue-cli 的 webpack 模板下,默认配置是:
transformToRequire: {
video: ['src', 'poster'],
source: 'src',
img: 'src',
image: 'xlink:href'
}
复制代码
能够触类旁通进行一下相似的配置
vue-loader 还有不少实用的 API 例如最近加入的 自定义块,感兴趣的各位能够去文档里找找看。
在某些场景下你可能须要 render 渲染函数带来的彻底编程能力来解决不太容易解决的问题,特别是要动态选择生成标签和组件类型的场景。
好比根据props来生成标签的场景
<template><div><divv-if="level === 0"><slot></slot></div><pv-else-if="level === 1"><slot></slot></p><h1v-else-if="level === 2"><slot></slot></h1><h2v-else-if="level === 3"><slot></slot></h2><strongv-else-if="level === 4"><slot></slot></stong><textareav-else-if="level === 5"><slot></slot></textarea></div></template>
复制代码
其中level是data中的变量,能够看到这里有大量重复代码,若是逻辑复杂点,加上一些绑定和判断就更复杂了,这里能够利用 render 函数来对要生成的标签加以判断。
使用 render 方法根据参数来生成对应标签能够避免上面的状况。
<template><div><child:level="level">Hello world!</child></div></template><scripttype='text/javascript'>import Vue from'vue'
Vue.component('child', {
render(h) {
const tag = ['div', 'p', 'strong', 'h1', 'h2', 'textarea'][this.level]
return h(tag, this.$slots.default)
},
props: {
level: { type: Number, required: true }
}
})
exportdefault {
name: 'hehe',
data() { return { level: 3 } }
}
</script>
复制代码
示例能够查看 CodePen
固然render函数还有不少用法,好比要使用动态组件,除了使用 :is
以外也可使用render函数
<template><div><button @click='level = 0'>嘻嘻</button><button @click='level = 1'>哈哈</button><hr><child:level="level"></child></div></template><scripttype='text/javascript'>import Vue from'vue'import Xixi from'./Xixi'import Haha from'./Haha'
Vue.component('child', {
render(h) {
const tag = ['xixi', 'haha'][this.level]
return h(tag, this.$slots.default)
},
props: { level: { type: Number, required: true } },
components: { Xixi, Haha }
})
exportdefault {
name: 'hehe',
data() { return { level: 0 } }
}
</script>
复制代码
示例能够查看 CodePen
网上的帖子大多深浅不一,甚至有些先后矛盾,在下的文章都是学习过程当中的总结,若是发现错误,欢迎留言指出~
参考: