如何通过 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
组件的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>
关于javascript - 如何从标准 JS 访问 Vue 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55925457/