简体   繁体   中英

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>

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM