简体   繁体   English

如何从标准 JS 访问 Vue 组件?

[英]How to access Vue component from standard JS?

How can I get access to a component's data via a window.addEventListener?如何通过 window.addEventListener 访问组件的数据? I want to hit the 'g' key and hide the Vue component test.我想按“g”键并隐藏 Vue 组件测试。

JS: 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:

<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 .created的组件的生命周期钩子中添加监听器。 This will give you access to the instance, including the visible data property.这将使您能够访问实例,包括visible数据属性。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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