【问题标题】:Using Vue to listen to DOM events outside of the app使用 Vue 监听应用外的 DOM 事件
【发布时间】:2019-02-10 09:29:46
【问题描述】:

我需要使用 Vue.js 逐步增强现有的服务器端渲染表单。我需要根据表单上另一个字段的值更改<select><options>

正如我所见,我无法在父 <form>(或另一个父元素)上安装 Vue,因为我丢失了所有服务器端渲染的内容,我需要维护这些内容。 p>

我已经安装了我希望动态化的<select>。这使我可以根据需要动态生成<option>s。然而,另一个表单输入元素(已安装的<select> 的兄弟)现在不在我的 Vue 范围内。如何提醒我的 Vue 应用程序依赖字段的更改,以便它可以相应地更新我的<option>s?

据我了解,Vue 有自己的事件系统,所以我必须自己连接一个 DOM 事件监听器——这完全没问题。这就是我目前所了解的。

除此之外:我明白,如果有无限的时间、金钱和资源,我应该顺应趋势,让我的整个用户体验成为一个 SPA,这将在火箭发射器到锤击钉子排序中解决这个问题的方式。然而,这不是一个选择。我必须逐步增强 SSR 输出。

【问题讨论】:

  • I cannot mount Vue on the parent <form> (or another parent element) as I lose all my server-side rendered content, which I need to maintain. 为什么? Vue 不需要挂载到空的 div。

标签: javascript vue.js


【解决方案1】:

您仍然可以使用 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>

【讨论】:

    猜你喜欢
    • 2020-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-02
    相关资源
    最近更新 更多