1

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?

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

ah, ok - the reason for that: "Unlike regular functions, arrow functions don’t have their own this or arguments binding. Instead, those identifiers are resolved in the lexical scope like any other variable."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.