【问题标题】:How to access to the Vuejs function by combining jQuery如何结合jQuery访问Vuejs功能
【发布时间】:2020-12-05 11:01:28
【问题描述】:

我正在使用LaravelVuejs 做一个小项目,一切都很好,我喜欢这两个框架。当我尝试使用 jQuery $.each 访问 goToStep 函数时,我遇到了一个小错误。

顺便说一句,jQuery 已经包含在内并且可以正常工作。唯一的问题是我无法在$.each 中访问goToStep

错误信息:

Uncaught (in promise) TypeError: this.goToStep is not a function

我的 VuejS 代码:

store: function () {
            axios.post("/apartment/", $("form#add-apartment").serialize()).then((response) => {
                this.buildings = response.data.buildings;
                alert(response.message)
            }).catch(error => {
                //console.log(error.response.data.errors)
                $.each(error.response.data.errors, function(key, value){
                    var x = $("[name='"+ key +"']").closest("#parent").data('step');
                    this.goToStep(x)
                });
            });
        },
        goToStep: function (value) {
            if (!this.validate()) {
                return;
            }
            this.current_step = value;
        },

【问题讨论】:

  • function(key, value) { 更改为(key, value) => { 以封装this 上下文围绕$.each。更多信息here
  • 非常感谢您,已修复

标签: javascript jquery vue.js


【解决方案1】:

替换

$.each(error.response.data.errors, function(key, value){
   var x = $("[name='"+ key +"']").closest("#parent").data('step');
   this.goToStep(x)
});

...与:

$.each(error.response.data.errors, key => this.goToStep(
  $(`[name='${key}']`).closest('#parent').data('step')
));

我做了什么:

  • arrow function 替换了您的匿名函数,因此外部this 在其中可用
  • 删除了value(第二个)参数,因为您没有在函数内的任何地方使用它
  • 删除了 var 声明(如果您只引用一次,则声明它没有意义 - 您可以简单地将引用替换为分配给 var 的实际代码,同时避免上下文污染)。
  • 将字符串连接替换为 template literals - 减小大小并提高可读性,恕我直言

【讨论】:

  • 如果我想使用 value 怎么办?
  • @Alice,你把它加回来:(key, value) => this.goToStep(...)。我只是删除它,因为它没有被使用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-19
  • 1970-01-01
  • 2011-01-26
  • 1970-01-01
  • 2019-09-12
  • 2022-09-25
相关资源
最近更新 更多