使用默认值合并Vue props

Mik*_*kko 7 javascript vue.js vue-component

我的Vue组件中有一个选项prop,它有一个默认值.

export default {
  props: {
    options: {
      required: false,
      type: Object,
      default: () => ({
        someOption: false,
        someOtherOption: {
          a: true,
          b: false,
        },
      }),
    },
  },
};
Run Code Online (Sandbox Code Playgroud)

如果options对象作为prop传递给组件,则替换默认值.例如,传递时{ someOption: true },现在options对象仅包含该值.

如何传递部分对象并使用给定值覆盖默认值而不是替换整个对象?

Cri*_*ora 13

我最近遇到了类似的问题并使用了Object.assign 以下是来自mozilla的文档https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

你案件的具体用法是这样的:

props: {
 options: {
  required: false,
  type: Object,
  default: () => ({}),
 },
},
data(){
  mergedOptions:{},
  defaultOptions:{
    someOption: false,
    someOtherOption: {
      a: true,
      b: false,
    },
  }
},
mounted(){
  //you will have the combined options inside mergedOptions
  Object.assign(this.mergedOptions,this.defaultOptions,this.options)
}
Run Code Online (Sandbox Code Playgroud)

通过这样做,您将只覆盖通过props传递的属性.不知道它是否是最有效的方式,但它是非常容易理解和整洁的:)

因此,如果您作为道具传入:options={someOption:true}合并的选项将等效于:

{
 someOption: true,
 someOtherOption: {
  a: true,
  b: false,
 },
}
Run Code Online (Sandbox Code Playgroud)

编辑:如果您需要数据被动,您可能想要计算.

  computed: {
    mergedOptions(){
      return {
       ...this.defaultOptions,
       ...this.options
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)