【问题标题】:vue findIndex not a functionvue findIndex 不是函数
【发布时间】:2018-12-18 23:58:41
【问题描述】:

这里我在findIndex() 函数中遇到错误

Uncaught (in promise) TypeError: state.carts.findIndex is not a function

cartId 有 r​​owId 和 qty 以及 sizeVal 和 image

方法

    updateCart() {
        this.$store.dispatch('updateCart', this.cartId)
    }

state: {
    carts: [],
},

Vue 检查推车

031e0275ef3746070e80d81199bd2580:Object {
    id:1
    name:"T-Shirt"
    options:Object {
        image:"products\July2018\4TXSMgf6eAdrOlaxAMiX.jpg"
    }
    size:"l"
    price:551
    qty:2
    rowId:"031e0275ef3746070e80d81199bd2580"
    subtotal:1102
    tax:115.71
}

变异

    updateCart(state, rowId) {
        const index = state.carts.findIndex(cart => {cart.rowId == rowId});
        // console.log(index)
            state.carts.splice(index, 1, {
                'qty': cart.qty,
                'size': cart.sizeVal,
            })
    },

在我的行动中是工作

操作

    updateCart(context, cart) {
        return new Promise((resolve, reject) => {
            axios.patch(`update/cart/${cart.id}` , {
                id: cart.rowId,
                qty: cart.qty,
                size: cart.sizeVal,
                image: cart.image
            })
            .then(response => {
                context.commit('updateCart', response.data)
                resolve(response)
            })
            .catch(error => {
                reject(error)
            })
        })

    },

现在我需要在 state.carts 中更新购物车的错误 需要帮助,请大家了解一下为什么它给了我错误

谢谢

【问题讨论】:

    标签: javascript vue.js cart vuex


    【解决方案1】:

    在 Vue 中使用 PolyFill 作为全局导入的 mixin。

     const findIndex = (values, expectedValue) => {
        let selectedIndex;
        const valuePresent = values.some((value, index) => {
          selectedIndex = index;
          return value === expectedValue;
        });
        return valuePresent ? selectedIndex : -1;
      };
    

    【讨论】:

      【解决方案2】:

      findIndex 是 ES6 数组功能,请确保您的浏览器支持它,或者您应该对其应用 polyfill 或 transpile 插件(如 babel.js)。

      【讨论】:

      • 在浏览器控制台上测试 [].findIndex,如果是函数,则检查 state.carts instanceof Array。
      【解决方案3】:

      您的state.carts 是一个对象,而不是一个数组。 findIndexarray method

      findIndex() 方法返回数组中满足提供的测试函数的第一个元素的索引。否则返回 -1。

      【讨论】:

      • 能否请您发布文字而不是图片。谷歌机器人无法真正抓取该图像。
      • 我更喜欢图片,因为它是文档的屏幕截图。证明我没有修改任何东西。
      • 引用应该注意这一点,可能由文档链接。介意我尝试编辑吗?
      • 请给我一个堆栈溢出指南的链接。如果正确,我会更新。
      • 没有确切的指导方针说你不能添加图片,这主要是为了让人们可以通过搜索引擎找到帖子。 The guidelines 确实要说总是引用重要链接中最相关的部分,以防目标站点无法访问或永久离线。 但我想图片还可以
      猜你喜欢
      • 2021-01-30
      • 1970-01-01
      • 2019-04-08
      • 1970-01-01
      • 2021-05-22
      • 2021-03-14
      • 2019-02-15
      • 2017-08-21
      • 2017-07-09
      相关资源
      最近更新 更多