[英]vue.js element selected by focus is not reactive
我有一個監聽器來檢查最后選擇了什么輸入,以便稍后添加某種字符串/變量。
created: function () {
document.addEventListener('focusin', this.focusChanged);
}
focusChanged(event) {
if (event.target.id !== 'variable-search') {
this.lastElement = event.target;
}
}
這似乎工作正常,當我單擊輸入字段時, this.lastElement
會使用焦點元素進行更新。 所有這些輸入都有一個v-model
,它可以是對象中的字符串,也可以是純字符串。
現在問題是當我嘗試通過以下方式更新值時:
this.lastElement.value += variable;
Vue 不會檢測到它的變化,同樣在 Vue 開發者工具中,字符串也不會被更新。 但是在輸入字段中它確實得到了更新。 所以這應該是一個反應性的事情。
當我在輸入字段(v-model)中添加一個新字符時,它會再次更新。 所以只是當我通過this.lastElement
更新字符串時,它不會注冊它的更改。
問題是輸入字段是動態的,所以我不知道這里有多少個輸入字段,有多少個列表等。所以我需要 Vue 在lastElement
的值更新后重新渲染變量。
編輯
我只是用@focus在這里嘗試了一個例子
<input v-model="testVar" @focus="lastElement = testVar">
如果我稍后更新lastElement
,它不會為testVar
更新它,而只是為lastElement
更新它。
您可以為每個輸入添加一個ref
屬性,並使用 ref 更新它們的值。 例如,輸入元素可以是:
<input v-model="testVar" ref="input1" id="input1" @focus="focusChanged">
在你的方法中:
methods: {
focusChanged(event) {
if (event.target.id !== 'variable-search') {
this.lastElement = event.target.id;
}
},
}
以及要更新值的位置: this.$refs[this.lastElement].value += variable;
以編程方式更改 DOM 元素中的值不會觸發 DOM 事件。 v-model
依賴input
(或使用.lazy
時change
)事件來更新其綁定變量。 如果您在更新輸入中的值時調度這些事件,則變量將做出反應。
new Vue({ el: '#app', data: { items: ['one','two','three'] }, methods: { addAddress() { this.lastElement.value += 'address'; this.lastElement.dispatchEvent(new Event('input')); this.lastElement.dispatchEvent(new Event('change')); }, focusChanged(event) { this.lastElement = event.target; } } })
<script src="https://unpkg.com/vue@latest/dist/vue.js"></script> <div id="app"> <div v-for="item, index in items"> <input v-model="items[index]" @focus="focusChanged"> {{item}} </div> <button type="button" @click="addAddress">+address</button> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.