【问题标题】:Use indexOf method with Vuejs在 Vuejs 中使用 indexOf 方法
【发布时间】:2019-02-22 12:50:29
【问题描述】:

我的 vue js 元素中有一个方法:

_deleteDesign : function(dsn)
{
    //_deleteDesign
    var url = '{{ url('/fapi/designsTmp/') }}/'+dsn.design_id;
    axios.delete(url)
    .then(function(){ 
        this.$delete(this.creations, this.creations.indexOf(function(el){
            return el.design_id = dsn.design_id;
        }));
    })
    .catch(function(e){
        alert('error deleting design');
    })
    debugger;
}

在这个方法中我使用的是Javascript的indexOf函数,但是vuejs在Chrome调试器中报告了这个错误:

this.creations.indexOf 不是函数

有什么问题?

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component


    【解决方案1】:

    由于新的函数声明,this 上下文在 promise then 处理程序中发生了变化。一种解决方法是使用 ES6 箭头函数,该函数将现有的 this 绑定保留在函数内:

           .then(() => { 
                 this.$delete(this.creations, this.creations.indexOf(function(el){
                    return el.design_id = dsn.design_id;
                 }));
              })
    

    【讨论】:

      【解决方案2】:

      “indexOf”方法只能对“string”或“array”类型的变量(实际上是“object”类型)执行。

      因此,在您的特定情况下,“this.creations”必须是数组或字符串。问题是,当“this.creations”不是这些类型之一时,您以某种方式结束了这种情况。

      一种可能的解决方案是添加

      console.log(typeof this.creations)

      并监控这个变量的类型。

      正如之前的回答所提到的,问题是“this”改变了上下文。一种解决方案是复制此对象: const self = this;

      在_deleteDesign 函数的开头并使用“self”对象而不是“this”。一般尽量避免使用“this”对象。

      【讨论】:

        猜你喜欢
        • 2023-01-22
        • 2018-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多