vue简洁好用体现在很多个地方,比如其内置了32+修饰符,可以很方便我们阻止冒泡、阻止默认事件、鼠标事件处理、系统键盘事件等等,让我们可以快速搞定业务,简直不要太方便噢!!!
耽误您15分钟您可以收获:
-
32+修饰符(包括事件修饰符、鼠标修饰符、表单修饰符、系统修饰符等等)的含义和使用
-
如何利用webpack动态注册vue路由,再也不手写路由配置啦!
http://www.360doc.com/content/21/1104/07/46403850_1002672849.shtml
https://gitee.com/numerical-control-system
如何动态注册路由?
文中的每个修饰符例子都由一个页面承载,聪明的你肯定不想手动引入几十个.vue文件并配置路由.
有什么办法可以帮我们自动完成路由注册呢?
1. 文件目录结构
目录结构(已去除其他文件目录)大概如下
├── package.json
└── src
├── App.vue
├── main.js
├── router.js
└── views
├── About.vue
├── Home.vue
└── modifiers
├── capture.vue
├── once.vue
├── order.vue
├── passive.vue
├── prevent.vue
├── self.vue
└── stop.vue
└── ...
复制代码
2. 期望的路由配置
最终给到
vue-router
的配置大概长下面这个样子,每个配置最重要的部分分别是path
、name
和component
[
{
"path": "/home",
"name": "home",
"component": {
"name": "Home",
"methods": {},
"staticRenderFns": [],
"_compiled": true,
"_scopeId": "data-v-fae5bece",
"beforeCreate": [
null
],
"beforeDestroy": [
null
],
"__file": "src/views/Home.vue"
}
},
{
"path": "/modifiers/capture",
"name": "modifiersCapture",
"component": {
"name": "capture",
"methods": {},
"staticRenderFns": [],
"_compiled": true,
"_scopeId": "data-v-63b4eeee",
"beforeCreate": [
null
],
"beforeDestroy": [
null
],
"__file": "src/views/modifiers/capture.vue"
}
},
... // 其他路由配置
]
复制代码
3. require.context实现动态注册路由
借助webpack require.context 的能力,可以非常方便地实现上面目录到路由配置的映射工作,源码如下
const registerRoutes = () => {
const contextInfo = require.context('./views', true, /.vue$/)
const routes = contextInfo.keys().map((filePath) => {
// filePath 形如 ./Home.vue、./modifiers/capture.vue
// path我们希望是/home、/modifiers/capture
// 所以需要把开头的./和.vue都替换为空
const path = filePath.toLowerCase().replace(/^\.|\.vue/g, '')
// name的话将/home、/modifiers/capture转成小驼峰即可
// 把开头的/先替换掉,再把第一个/后的单词变成大写就可以了
const name = path.replace(/^\//, '').replace(/\/(\w)/, ($0, $1) => $1.toUpperCase())
// 通过require去读取.vue文件内容
const component = require(`./views${filePath.replace(/^\./, '')}`).default
return {
path,
name,
component
}
})
return routes
}
复制代码
效果
经过上面的简单处理,动态注册路由就完成啦!您也可以点击vue-demos查看效果
事件修饰符
1. 阻止冒泡的两种方式
<template>
<div class="parent" @click="onClickParent">
我是爸爸
<div class="child" @click="onClickChild">
我是儿子
</div>
</div>
</template>
export default {
name: 'stop',
methods: {
onClickParent () {
console.log('我是爸爸')
},
onClickChild () {
console.log('我是儿子')
}
}
}
复制代码
点击子节点的时候因为事件冒泡的缘故不仅会打印出我是儿子
还会打印我是爸爸
。有什么办法可以阻止子节点的事件冒泡呢?
1 .stop
只要加.stop修饰符即可,阻止事件冒泡的及简方式,很方便是不是。
当添加上.stop
修饰符时,只会出现我是儿子