【问题标题】:jQuery with Vue.js - $(this) is not working in method带有 Vue.js 的 jQuery - $(this) 在方法中不起作用
【发布时间】:2019-03-13 20:42:51
【问题描述】:

首先,我知道将 jQuery 与 Vue 混合并不是一个好主意。但是,我仍然尝试在单击后对元素执行某些操作,但 $(this) 不起作用。

methods: {
  openSMS() {
    $(this).hide(); // <-- not working here..
    // More code...
  },
  addEventListeners() {
    $(document).ready(function() {
      $(".ml-inbox-msg-item").click(function() {
        // $(this).hide() <-- it works here
        InboxSidebar.openSMS();
      });
    });
  }
}

一个页面上有很多.ml-inbox-msg-item元素。

如果我将$(this).hide() 放在.click 函数中,那么它就可以工作。有没有办法将它传递给openSMS() 函数?

【问题讨论】:

    标签: javascript jquery vue.js


    【解决方案1】:

    这是因为openSMS() 的作用域与click 处理函数的作用域不同。假设您可以更改方法签名,修改 openSMS() 以接受元素引用作为参数:

    methods: {
      openSMS(el) {
        $(el).hide();
      },
      addEventListeners() {
        $(document).ready(function() {
          $(".ml-inbox-msg-item").click(function() {
            InboxSidebar.openSMS(this);
          });
        });
      }
    }

    【讨论】:

    • 谢谢!那行得通!这正是我想要的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    • 2014-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多