一、善用watch的immediate属性
这一点我在项目中也是这么写的。例如有请求需要再也没初始化的时候就执行一次,然后监听他的变化,很多人这么写:
created(){
this.fetchPostList()
},
watch: {
searchInputValue(){
this.fetchPostList()
}
}
上面的这种写法我们可以完全如下写:
watch: {
searchInputValue:{
handler: 'fetchPostList',
immediate: true
}
}
二、精简vuex的modules引入
对于vuex,我们输出store如下写:
import auth from './modules/auth'
import posts from './modules/posts'
import comments from './modules/comments'
// ...
export default new Vuex.Store({
modules: {
auth,
posts,
comments,
// ...
}
})
要引入好多modules,然后再注册到Vuex.Store中~~
精简的做法和上面类似,也是运用 require.context()读取文件,代码如下:
import camelCase from 'lodash/camelCase'
const requireModule = require.context('.', false, /\.js$/)
const modules = {}
requireModule.keys().forEach(fileName => {
// Don't register this file as a Vuex module
if (fileName === './index.js') return
const moduleName = camelCase(
fileName.replace(/(\.\/|\.js)/g, '')
)
modules[moduleName] = {
namespaced: true,
...requireModule(fileName),
}
})
export default modules
这样我们只需如下代码就可以了:
import modules from './modules'
export default new Vuex.Store({
modules
})
三、唯一组件根元素
场景如下:
(Emitted value instead of an instance of Error)
Error compiling template:
<div></div>
<div></div>
-Component template should contain exactly one root element.
If you are using v-if on multiple elements, use v-else-if
to chain them instead.
模板中div只能有一个,不能如上面那么平行2个div。
例如如下代码:
<template>
<li
v-for="route in routes"
:key="route.name"
>
<router-link :to="route">
{{ route.title }}
</router-link>
</li>
</template>
会报错!
我们可以用render函数来渲染
functional: true,
render(h, { props }) {
return props.routes.map(route =>
<li key={route.name}>
<router-link to={route}>
{route.title}
</router-link>
</li>
)
}
四、组件包装、事件属性穿透问题
当我们写组件的时候,通常我们都需要从父组件传递一系列的props到子组件,同时父组件监听子组件emit过来的一系列事件。举例子:
//父组件
<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>
//前端全栈学习交流圈:
//面向1-3经验年前端开发人员
//帮助突破技术瓶颈,提升思维能力
这样写很不精简,很多属性和事件都是手动定义的,我们可以如下写:
<input
:value="value"
v-bind="$attrs"
v-on="listeners"
>
computed: {
listeners() {
return {
...this.$listeners,
input: event =>
this.$emit('input', event.target.value)
}
}
}
$attrs
包含了父作用域中不作为 prop 被识别 (且获取) 的特性绑定 (class 和 style 除外)。当一个组件没有声明任何 prop 时,这里会包含所有父作用域的绑定,并且可以通过 v-bind="$attrs" 传入内部组件。
$listeners
包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器。它可以通过 v-on="$listeners" 传入内部组件。