vue鍵盤事件點選事件加native
<el-card class="box-card animated flipInY"> <el-form :model="ruleForm2" :label-position="labelPosition" status-icon :rules="rules2" ref="ruleForm2" label-width="50px" class="demo-ruleForm"> <h3 class="login_title">系統登入</h3> <el-form-item label="賬號" prop="account"> <el-input type="text" v-model="ruleForm2.account" @keyup.native.enter="handleSubmit2" auto-complete="off" placeholder="賬號"></el-input> </el-form-item> <el-form-item label="密碼" prop="checkPass"> <el-input type="password" v-model="ruleForm2.checkPass" @keyup.native.enter="handleSubmit2" auto-complete="off" placeholder="密碼"></el-input> </el-form-item> <el-checkbox label="記住密碼" v-model="checked" class="remember">記住密碼</el-checkbox> <el-form-item > <el-button type="primary" class="login_btn" @click.native.prevent="handleSubmit2" :loading="logining">登入</el-button> </el-form-item> </el-form> </el-card>
如上程式碼,後臺管理系統的登入。在賬號和密碼中加入了鍵盤enter事件,監聽時需要加.native才能正確使用;下面按鈕的點選事件同樣要加.native才能正常使用。
參考官方文件:
你可能有很多次想要在一個元件的根元素上直接監聽一個原生事件。這時,你可以使用 v-on
的 .native
修飾符:
<base-input v-on:focus.native="onFocus"></base-input>
在有的時候這是很有用的,不過在你嘗試監聽一個類似 <input>
的非常特定的元素時,這並不是個好主意。比如上述 <base-input>
元件可能做了如下重構,所以根元素實際上是一個 <label>
元素:
<label> {{ label }} <input v-bind="$attrs" v-bind:value="value" v-on:input="$emit('input', $event.target.value)" > </label>
這時,父級的 .native
監聽器將靜默失敗。它不會產生任何報錯,但是 onFocus
處理函式不會如你預期地被呼叫。
為了解決這個問題,Vue 提供了一個 $listeners
屬性,它是一個物件,裡面包含了作用在這個元件上的所有監聽器。例如:
{ focus: function |
有了這個 $listeners
屬性,你就可以配合 v-on="$listeners"
將所有的事件監聽器指向這個元件的某個特定的子元素。對於類似 <input>
的你希望它也可以配合 v-model
工作的元件來說,為這些監聽器建立一個類似下述 inputListeners
的計算屬性通常是非常有用的:
Vue.component('base-input', { inheritAttrs: false, props: ['label', 'value'], computed: { inputListeners: function () { var vm = this // `Object.assign` 將所有的物件合併為一個新物件 return Object.assign({}, // 我們從父級新增所有的監聽器 this.$listeners, // 然後我們新增自定義監聽器, // 或覆寫一些監聽器的行為 { // 這裡確保元件配合 `v-model` 的工作 input: function (event) { vm.$emit('input', event.target.value) } } ) } }, template: ` <label> {{ label }} <input v-bind="$attrs" v-bind:value="value" v-on="inputListeners" > </label> ` }) |
現在 <base-input>
元件是一個完全透明的包裹器了,也就是說它可以完全像一個普通的 <input>
元素一樣使用了:所有跟它相同的特性和監聽器的都可以工作。
這裡直接將官方文件copy過來了,也就是說當我們要監聽元件的鍵盤事件或者點選事件的時候是不需要加.native的,而監聽元件的就需要加.native才能使用了;但當你需要監聽的內容是元件的子元素的時候.native也是不會生效的,此時官方又給了處理的辦法就是使用v-on="$listeners"。