# 简介
Vue 提供了事件绑定的语法糖,我们在标签中可直接使用形如 v-on:click,@click,@focus 的形式绑定事件监听器,并且可以使用修饰符对事件进行 option 设置。本次解释 once 修饰符以及 native 修饰符的情况。
# once
绑定 once 的监听器只会触发一次,在第一次触发后该监听器会被 remove 掉。很简单不多做解释了。
# native
我们可以称 native 为原型绑定。只有使用 vue 组件时我们会用到这个修饰符。当我们在组件上绑定监听时,我们绑定的是组件定义的监听。以 element 框架为例,<el-input> 是 element 提供的组件。它在浏览器解析后是这样的。我们写 < el-input @click=""> 时,这 click 绑定的是 element 给 el-input 定义的方法。我们其实把 click 绑定在了 **div [class="el-input"]** 上了。
与直接在 <input> 上绑定是不同的,
如果 element 没给 el-input 定义 click,那么我们这次绑定是无效的。
当我们加上 native 词缀,<el-input @click.native=""> 这样,我们就把 click 事件直接绑定在了原型上了,也就是绑定在
input [class="el-input__inner"]
上了。这是我们绑定的就和 input 标签的原生监听器是一样的。所以当我们使用组件时需要经常使用原型绑定。
通俗点讲:
就是在父组件中给子组件绑定一个原生的事件,就将子组件变成了普通的 HTML 标签,不加 **. native** 事件是无法触 发的。
<template> | |
<div> | |
<my-component @click="outClick"></my-component> | |
</div> | |
</template> | |
<script> | |
import Vue from 'vue' | |
Vue.component('my-component', { | |
template: `<el-button type="primary">InnerButton</el-button>` | |
}) | |
export default { | |
methods: { | |
outClick: { | |
alert('this is outer') | |
} | |
} | |
} | |
</script> |
此时点击页面中的按钮无任何反应。
添加修饰符:
<template> | |
<div> | |
<my-component @click.native="outClick"></my-component> | |
</div> | |
</template> | |
<script> | |
import Vue from 'vue' | |
Vue.component('my-component', { | |
template: `<el-button type="primary">InnerButton</el-button>` | |
}) | |
export default { | |
methods: { | |
outClick: { | |
alert('this is outer') | |
} | |
} | |
} | |
</script> |
此时点击就会弹窗