首页 > 解决方案 > 如何结合jQuery访问Vuejs功能

问题描述

我正在使用一个小项目LaravelVuejs一切都很好,我喜欢这两个框架。当我尝试goToStep使用jQuery $.each.

顺便说一句jQuery,已经包括在内并且工作正常。唯一的问题是我无法进入goToStep里面$.each

错误信息 :

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;
        },

标签: javascriptjqueryvue.js

解决方案


代替

$.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')
));

我做了什么:

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

推荐阅读