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

时间:2019-04-30 16:47:04

标签: javascript vue.js

如何通过window.addEventListener访问组件的数据? 我想按'g'键并隐藏Vue组件测试。

JS:

import requests
from bs4 import BeautifulSoup as bs
import urllib.parse
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


url = 'https://stackoverflow.com/tags/{}/popup'
page_url = 'https://stackoverflow.com/tags?page={}'
results = []
d = webdriver.Chrome()

with requests.Session() as s:
    r = s.get('https://stackoverflow.com/tags')
    soup = bs(r.content, 'lxml')
    num_pages = int(soup.select('.page-numbers')[-2].text)

    for page in range(1, 3): # for page in range(1, num_pages + 1):
        if page > 1:
            r = d.get(page_url.format(page))
            WebDriverWait(d,10).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, '.stats-row a')))
            soup = bs(d.page_source, 'lxml')

        tags = [(item.text, urllib.parse.quote(item.text)) for item in soup.select('.post-tag')]
        how_many  = [item.text for item in soup.select('.stats-row a')]
        frequency1 = how_many[0::2]
        frequency2 = how_many[1::2]
        i = 0
        for tag in tags:
            r = s.get(url.format(tag[1]))
            soup = bs(r.content, 'lxml')
            description = soup.select_one('div:not([class])').text
            stats = [item['title'] for item in soup.select('[title]')]
            total_watchers = stats[0]
            total_questions = stats[1]
            row = [tag[0], description, total_watchers, total_questions, frequency1[i],  frequency2[i]]
            results.append(row)
            i+=1
df = pd.DataFrame(results, columns = ['Tag', 'Description', 'Total Watchers', 'Total Questions', 'Frequency1', 'Frequency2'])
d.quit()
print(df.head())

HTML:

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

2 个答案:

答案 0 :(得分:2)

created组件的life cycle hook中添加侦听器。这将使您可以访问实例,包括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>

答案 1 :(得分:1)

将逻辑放入组件内部

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