Home > database >  Howto modify Vue Data from vanilla JS event listener?
Howto modify Vue Data from vanilla JS event listener?

Time:09-30

I've got a barcode scanner app based on a simple keyboard logger and some vue data I'd like to address in a proper way. Please have a look at the following simplified (working) sample. Is there a better way to access the packageA array than doing a var obj = this; to address my vue instance instead of document?

export default {
        name: "xxx",
        data() {
            return {
                packageA: []
            };
        },
        created: function () {
            var obj = this;
            document.addEventListener('keyup', function (e) {
                obj.packageA.push(e.key)
            });
        }
    } 

What would be a proper way to do this?

CodePudding user response:

You can use arrow function :

new Vue({
  el: "#demo",
  data() {
    return {
      packageA: []
    };
  },
  created() {
    document.addEventListener('keyup', (e) => {
      this.packageA.push(e.key)
    });
  }
}) 
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  {{ packageA }}
</div>

  • Related