Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue: when to use @keyup.native in input elements

I have a Vue component with

  1. an <input> element that binds the v-on:keyup.enter key to doFilter()
  2. a <button> that binds the v-on:click event to doFilter()
<input type="text" v-model="myVar" @keyup.enter="doFilter" />
<button @click="doFilter">Filter</button>

The button event will fire doFilter(), but the key up event will not fire, unless I add the .native modifier.

<input type="text" v-model="myVar" @keyup.native.enter="doFilter" />

The Vue.js documentation says this about .native:

listen for a native event on the root element of component.

When do I need to use .native and why does the keyup event not trigger without it?

Update 1: Add codepen and code

Runnable demo at https://codepen.io/hanxue/pen/Zapmra

<div id="app">
  <md-toolbar>
    <h1 class="md-title" style="flex: 1">@keyup.native event</h1>
    <md-button class="md-icon-button">
      <md-icon>more_vert</md-icon>
    </md-button>
  </md-toolbar>
  
  <md-input-container>
      <label>@keyup.enter</label>
              <md-input type="text" @keyup.enter="doFilter" placeholder="@keyup.filter">
              </md-input>
          </md-input-container>
  
    <md-input-container>       
        <label>@keyup.native.enter</label>
              <md-input type="text" @keyup.native.enter="doFilter" placeholder="@keyup.native.filter">
              </md-input>
          </md-input-container>
  
    <md-input-container>       
              <button @click="doFilter" placeholder="@keyup.filter">
    @click  </button>
          </md-input-container>
</div>
<script>
Vue.use(VueMaterial)

var App = new Vue({
  el: '#app',
  methods: {
   doFilter: function() {
     alert('doFilter!')
   }
  },
})
</script>
like image 256
Hanxue Avatar asked Nov 07 '17 16:11

Hanxue


1 Answers

Based on your comments, I'm assuming that you're using the Vue Material libary and the <md-input> component instead of an <input> element.

If you listen to the keyup event without using the .native modifier (via <md-input @keyup.enter="doFilter">), then your component is waiting for the <md-input> component to emit a custom keyup event.

But, that component does not emit a keyup event, so the doFilter method will never be called.

As the documentation states, adding the .native modifier will make the component listen for a "native event on the root element" of the <md-input> component.

So, <md-input @keyup.native.enter="doFilter"> will listen to the native keyup DOM event of the root element of the <md-input> component and call the doFilter method when that is triggered from the Enter key.

like image 77
thanksd Avatar answered Nov 02 '22 23:11

thanksd