root element is undefined while pagination

183 Views Asked by At

I ma using element ui el-pagination like this

<el-pagination
        @size-change="handleChange"
        @current-change="CurrentChange"
        :current-page.sync="currentPage"
        :page-sizes="[50, 100, 150, 300]"
        :page-size="pageSize"
        popper-class="popper"
        layout="sizes, prev, pager, next"
        :total="getTotal"
      />

i have the methods defined

CurrentChange(val) {
      this.currentPage = val;
    },

i have created a mixin called as pagination.js

because this pagination is used at many places, so i added some keyboard events in it like this

document.querySelectorAll('ul.el-pager li.number').forEach((element, index) => {
       
        element.addEventListener('keyup', function (e) {
          if (e.key == 'Enter' || e.key == 'Space') {
            this.$root.CurrentChange(element.innerHTML);
          }
        });
      })

but i am getting undefined

i tried the console.log(this.$root) and i getting undefined, what i am missing here, i though the root has all the vue can fetch from

1

There are 1 best solutions below

6
Mina On

this inside the keyup event handler will refer to the element itself, not the component instance, you need to get this value ( as the component instance ) from outside the forEach callback function.

const that = this;

document.querySelectorAll('ul.el-pager li.number').forEach((element, index) => {
   
    element.addEventListener('keyup', function (e) {
      if (e.key == 'Enter' || e.key == 'Space') {
        that.$root.CurrentChange(element.innerHTML);
      }
    });
  })