Gabriel
Gabriel

Reputation: 5723

How to access Vue component from standard JS?

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>

Upvotes: 0

Views: 157

Answers (2)

Ricky Ruiz
Ricky Ruiz

Reputation: 26761

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>

Upvotes: 2

Ohgodwhy
Ohgodwhy

Reputation: 50787

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

Upvotes: 1

Related Questions