0

How can I get access to a component's data via a window.addEventListener? I want to hit the 'g' key and hide the Vue component test.

JS:

window.onload = function () {
  Vue.component('test', {
    template: `<div id="box" v-if="visible"></div>`,
    data() {
      return {
        visible: true
      }
    }
  })
  var app = new Vue({
    el: '#app'
  });
  window.addEventListener('keydown', (e) => {
    if (e.key == 'g') {
      //set test.visible = false
    }
  });
  window.app = app;
}

HTML:

<html>
<head>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="code.js"></script>
  <link rel="stylesheet" type="text/css" href="styles.css" />

</head>

<body>
  <div id="app">
    <test></test>
  </div>
</body>
</html>

2 Answers 2

2

Add the listener in the created component's life cycle hook. This will give you access to the instance, including the visible data property.

Make sure to also remove the listener once your component is destroyed.

window.onload = function() {
  Vue.component('test', {
    template: `<div id="box" v-if="visible"></div>`,

    data() {
      return {
        visible: true
      }
    },

    created() {
      window.addEventListener('keydown', this.visibilityHandler)
    },

    destroyed() {
      window.removeEventListener('keydown', this.visibilityHandler)
    },

    methods: {
      visibilityHandler(e) {
        if (e.key == 'g') {
          this.visible = false
        }
      }
    },
  });

  var app = new Vue({
    el: '#app'
  });

  window.app = app;
}
#box {
  width: 100px;
  height: 100px;
  border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <test></test>
</div>

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

2 Comments

Gracias @Ricky, worked beautifully. I'm starting to dig into these new JS frameworks.
De nada! Make sure to keep asking questions if you have any doubts.
1

Put the logic inside of the component:

Vue.component('test', {
  template: `<div id="box" v-if="visible"></div>`,
  data() {
    return {
      visible: true
    }
  },
  mounted() {
    window.addEventListener('keydown', (e) => {
      if (e.key == 'g') {
        this.visible = false
      }
    });
  }
})

Comments

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.