簡體   English   中英

如何從標准 JS 訪問 Vue 組件?

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

如何通過 window.addEventListener 訪問組件的數據? 我想按“g”鍵並隱藏 Vue 組件測試。

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>

created的組件的生命周期鈎子中添加監聽器。 這將使您能夠訪問實例,包括visible數據屬性。

確保在您的組件被銷毀后也刪除偵聽器。

 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>

將邏輯放在組件內部:

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