我想收听我的VUE应用程序上的所有焦点事件。为了获取当前重点的输入,我考虑过将document.activeElement
属性绑定到我的应用程序组件中的计算属性,但这不是反应性,为什么?
声明数据中的活动元素也不反应。
对于观察者来说同一件事!
使其工作的唯一方法是,只需在输入本身就焦点/模糊事件之后返回值,但这并不适合我的需求。
new Vue({
el: "#app",
data: {
activeElem: document.activeElement.tagName,
realActiveElem: document.activeElement.tagName,
},
methods: {
getActiveElem() {
this.realActiveElem = document.activeElement.tagName;
}
},
computed: {
focused() {
return document.activeElement.tagName;
}
},
watch: {
activeElem(val, oldVal) {
console.log(val !== oldVal);
},
focused(val, oldVal) {
console.log(val !== oldVal);
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<h2 @focus="getActiveElem()">
Data: {{activeElem}}
</h2>
<h2>
Computed: {{focused}}
</h2>
<h2>
From function to data: {{realActiveElem}}
</h2>
<input placeholder="Focus/Blur me" id="test" @focus="getActiveElem()" @blur="getActiveElem()" />
</div>
有什么方法可以将文档或窗口属性绑定为反应性?
vue只能对对数据的更改而不是对DOM做出反应。document.activeelement的更改是dom的变化。
您可以使用事件使用事件来更新数据。例如:
new Vue({
el: "#app",
data: {
element: ""
},
created() {
document.addEventListener("focusin", this.focusChanged);
},
beforeDestroy() {
document.removeEventListener("focusin", this.focusChanged);
},
methods: {
focusChanged(event) {
this.element = event.target.tagName;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input id="mine">
<p>{{ element }}</p>
</div>