Vue.js默认函数参数解构和'this'

时间:2019-11-19 15:38:49

标签: javascript vue.js

在尝试声明与解构结合的默认参数时,我用data引用this时遇到问题。有人知道怎么做吗?

activated () {
  this.fillData()
},

data () {
  return {
    chartData: {
      distributionInitialData: {
        // data here
      }
    }
  }
},

methods: {
  fillData ({
      must = this.chartData.distributionInitialData,
      nice = this.chartData.distributionInitialData
    }) {
    // do something
    // function doesn't even get here because it gets error:
    // TypeError: Cannot read property 'must' of undefined
    // at VueComponent.fillData (Component.vue?4e6a:230)
    // at VueComponent.activated (Component.vue?4e6a:123)
  }
}

3 个答案:

答案 0 :(得分:1)

您需要设置参数(对象)的默认值,而不是其属性。

db.POSTS.aggregate([{ $addFields: { "createdBy": { "$toObjectId": "$createdBy" } } }, {
    $lookup:
    {
        from: "USERS",
        localField: "createdBy",
        foreignField: "_id",
        as: "userDetails"
    }
}, {
    $addFields:
    {
        createdBy: {
            $cond: {
                if: { $ne: ["$userDetails", []] },
                then: { $arrayElemAt: ['$userDetails.name', 0] },
                else: { "$toString": "$createdBy" }
            }
        }
    }
}, { $project: { userDetails: 0 } }])

已更新,根据Bergi的建议。

methods: {
  fillData ({must, nice} = {
      must: this.chartData.distributionInitialData,
      nice: this.chartData.distributionInitialData
    }) {
    // do something
  }
}

仅供参考,这是一个简单的codepen

答案 1 :(得分:0)

可以。

fillData ({ must, nice}) {
    must = must || this.chartData.distributionInitialData
    nice = nice || this.chartData.distributionInitialData

    // do something
}

答案 2 :(得分:0)

因此,问题与Vue在创建组件时如何将方法绑定到组件有关。函数定义无权访问该实例,但是您可以在其中使用this

最简单的解决方案是根据所需的默认值立即检查未定义和设置的内容。

fillData({ must, nice }) {
    if (must === undefined) must = this.chartData.distributionInitialData;
    if (nice === undefined) nice = this.chartData.distributionInitialData;

    // any other code here
}

您还可以尝试使用箭头功能来查看它是否可以解决此问题,因为引入该功能是为了更具体地绑定到this。也许是这样的:

fillData = ({ 
    must = this.chartData.distributionInitialData, 
    nice = this.chartData.distributionInitialData 
}) => {
    // any other code here
}