簡體   English   中英

使用Vue監聽應用外部的DOM事件

[英]Using Vue to listen to DOM events outside of the app

我需要使用Vue.js逐步增強現有的服務器端呈現形式。 我需要根據表單上另一個字段的值來更改<select><options>

如我所見,由於丟失了所有需要維護的服務器端渲染內容,因此無法在父<form> (或另一個父元素)上安裝Vue。

我已經安裝了希望動態化的<select> 但是,這使我可以動態生成<option> 但是,另一個表單輸入元素(已安裝的<select>的同級元素)現在不在我的Vue范圍內。 如何通知我的Vue應用程序有關從屬字段的更改,以便它可以相應地更新<option>

據我了解,Vue有自己的事件系統,因此我將不得不自己連接DOM事件監聽器-完全可以。 就我所知。

另外:我了解在無窮的時間,金錢和資源的情況下,我應該遵循使我的整個用戶體驗成為SPA的趨勢,它將以一種從火箭發射器到錘子到釘子的方式解決此問題。 但是,這不是一個選擇。 我必須逐步增強SSR輸出。

您仍然可以使用document.querySelector()在文檔中查詢同級元素,並從Vue實例中調用addEventListener()

 const ALL_DATA = [ {id: 1, value: 1, text: 'One'}, {id: 2, value: 2, text: 'Two'}, {id: 3, value: 3, text: 'Three'}, ]; new Vue({ el: '#app', data: () => ({ options: [ ...ALL_DATA, ] }), mounted() { document.querySelector('#option-type').addEventListener('change', e => { switch (e.target.value) { case 'even': this.options = ALL_DATA.filter(x => x.value % 2 === 0); break; case 'odd': default: this.options = ALL_DATA.filter(x => x.value % 2 !== 0); break; } }) } }); document.getElementById('myForm').addEventListener('submit', e => { e.stopPropagation(); e.preventDefault(); }); 
 <script src="https://unpkg.com/vue@2.5.17"></script> <form action="#" id="myForm"> <fieldset id="option-type"> <label>Even <input name="option-type" type="radio" value="even"> </label> <label>Odd <input name="option-type" type="radio" value="odd"> </label> </fieldset> <select name="option" id="app"> <option v-for="o in options" value="o.value" :key="o.id">{{o.text}}</option> </select> </form> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM