【问题标题】:Jquery not working on Vue component used more than onceJquery 无法处理多次使用的 Vue 组件
【发布时间】:2021-12-02 20:11:36
【问题描述】:

我在 Vuejs 上创建了一个自定义日期时间选择器组件,并使用 jQuery 将父 div 滚动到所选数字。

由于我在一个页面中多次使用此日期时间选择器组件,因此 jQuery 只会正确影响页面上使用的第一个组件!

这是 vueJs 上日期时间选择器组件的一部分:

<div class="date-section-holder">
  <div class="years">
    <p v-for="year in years" :class="{'active': selectedYear === year}" @click="selectedYear = year">{{ year }}</p>
  </div>
  <div class="months">
    <p v-for="month in months" :class="{'active': selectedMonth === month}" @click="selectedMonth = month">{{ month }}</p>
  </div>
  <div class="days">
    <p v-for="day in days" :class="{'active' : selectedDay === day}" @click="selectedDay = day"> {{ day }}</p>
  </div>
</div>

这只是 jQuery 的一部分:

$('.days p').on('click', function() {
  $($(this).parent()).scrollTop($($(this).parent()).scrollTop() + $(this).position().top - 150);
});

还有 jQuery 在打开时对齐所有字段的部分,仅影响使用的第一个组件:

$(document).ready(function() {
  $('.days').scrollTop($('.days').scrollTop() + $($('.days').find('.active')).position().top - 150);
  $('.years').scrollTop($('.years').scrollTop() + $($('.years').find('.active')).position().top - 150);
  $('.months').scrollTop($('.months').scrollTop() + $($('.months').find('.active')).position().top - 150);
})

【问题讨论】:

  • 不要同时使用 jQuery 和 Vue js。
  • 你能控制你的 Vue 组件的滚动行为吗? jQuery 增加了一个新的复杂程度,这不是一个很好的设计模式。 Vue 内置了点击处理程序。

标签: jquery vue.js


【解决方案1】:

jQuery 不需要与Vue.js 一起使用,也不推荐使用,因为您可以通过Vue.js 操作 DOM 而不需要jQuery。你让它变得复杂。

您可以并且应该使用类似PrimeVue 的东西。它提供了很多组件,还有一个日历,您可以在其中选择日期和时间。您可以在此文档中找到有关它的更多信息:PrimeVue | Calendar

【讨论】:

    【解决方案2】:

    好吧,我不会告诉你不要同时使用 Vue 和 JQ,因为你已经知道了:)

    为了将 JQuery 与 Vue 或任何类似的框架一起使用,并且以组件的形式不断地重新绘制 dom 的一部分,您需要将事件侦听器附加到静态父 dom 元素。

    例如:

    $('.days p').on('click', function() {
      $($(this).parent()).scrollTop($($(this).parent()).scrollTop() + 
      $(this).position().top - 150);
    });
    

    应该是这样的:

    $(document).on('click', '.days p', function() {
      $($(this).parent()).scrollTop($($(this).parent()).scrollTop() + 
      $(this).position().top - 150);
    });
    

    对于第二部分,您可能需要在添加新组件时进行捕捉

    $(document).on('DOMNodeInserted', function(e) {
    
      var days = $(e.target).find('.days');
      var years= $(e.target).find('.years');
      var months= $(e.target).find('.months');
    
      if ( days .length ) {
        days.scrollTop(days.scrollTop() + $(days.find('.active')).position().top - 150);
      }
      if ( years.length ) {
        years.scrollTop(years.scrollTop() + $(years.find('.active')).position().top - 150);
      }
      if ( months.length ) {
        months.scrollTop(months.scrollTop() + $(months.find('.active')).position().top - 150);
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-23
      • 1970-01-01
      • 2019-08-11
      • 2020-12-03
      • 1970-01-01
      • 1970-01-01
      • 2018-12-06
      • 2011-01-15
      相关资源
      最近更新 更多