[Vuejs]-How to access Vue component from standard JS?

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>

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
      }
    });
  }
})

Leave a comment