vue 开发忽略的有用的技巧
hookEvent:

改造之后:
在Vue组件中,可以用过$on,$once去监听所有的生命周期钩子函数,如监听组件的updated钩子函数可以写成 this.$on('hook:updated', () => {})
document.addEventListener('click', this.hide);
this.$once('hook:beforeDestroy', this.hide);
外部监听生命周期函数

小项目用Vue.observable手写一个状态管理


1.require.context()
加载文件夹下所有的文件,例子: 将 global 文件夹下面所有的组件设置为全局组件,但是不包括 index.vue

index.js:
import Vue from 'vue'; // 自动加载 global 目录下的 .vue 结尾的文件 const componentsContext = require.context('./', true, /\.vue$/); componentsContext.keys().forEach(component => { if (component.startsWith('./index')) return; const componentConfig = componentsContext(component); const ctrl = componentConfig.default || componentConfig; Vue.component(ctrl.name, ctrl); });
2.watch

3.$attrs


4.$listeners
5.路由传参
// 路由定义
{
path: '/describe',
name: 'Describe',
omponent: Describe
}
// 方案1
this.$router.push({
path: `/describe/${id}`,
})
this.$route.params.id
// 方案2
this.$router.push({
name: 'Describe', // 必须设置路由名字
params: { id: id }
})
this.$route.params.id
// 方案3
this.$router.push({
path: '/describe',
query: {
id: id
`}
)
this.$route.query.id
方案二:必须设置路由名字;参数不会拼接在路由后面,页面刷新参数会丢失
方案一和三: 参数拼接在后面,丑,而且暴露了信息
6.异步组件
全局异步组件:

局部异步组件:

处理异步组件加载状态:

7.递归组件
递归组件: 组件在它的模板内可以递归的调用自己,只要给组件设置name组件就可以了。
必须给一个条件来限制数量,否则会抛出错误: max stack size exceeded

8.事件修饰符
.stop: 阻止冒泡 .prevent: 阻止默认行为 .self: 仅绑定元素自身触发 .once: 2.1.4 新增, 只触发一次 .passive: 2.3.0 新增,滚动事件的默认行为 (即滚动行为) 将会立即触发,不能和.prevent 一起使用
9.router-view 的 key

10. 样式的 <<<; scss中的deep属性
一般样式:

添加 <<<:

scss:



浙公网安备 33010602011771号