【问题标题】:Props interdependance in VueJSVueJS 中的 props 相互依赖
【发布时间】:2020-11-02 17:32:37
【问题描述】:

我想在我的 VueJS 组件中的 props 之间添加一些链接依赖项。

例如,在我的 props 声明组件中,我想规定,如果存在一个 prop,则应该需要另一个,但如果先前的 prop 不存在,则根本不需要。

props: {
    url: {
      type: String,
      required: true,
    },
    isShared: {
      type: Boolean,
      default: false,
    },
    isSharedByOtherMember: {
      type: Boolean,
      default: false,
    },
    archivedId: {
      type: String,
      required: isSharedByOtherMember ? true : false, // This is not working, bit is there a way to do so ?
    },

看完vuejs docs

请注意,在创建组件实例之前会验证 props,因此实例属性(例如数据、计算等)在默认或验证器函数中不可用。

有没有办法在道具声明中仍然这样做,以便在之后更好的可读性/可理解性?

提前致谢

【问题讨论】:

  • 我建议为每个依赖属性使用默认值。

标签: vue.js vuejs2


【解决方案1】:

您可以将验证器属性用于 prop。

Vue 文档有这个例子:(https://vuejs.org/v2/guide/components-props.html#Prop-Validation)

// Custom validator function
propF: {
  validator: function (value) {
    // The value must match one of these strings
    return ['success', 'warning', 'danger'].indexOf(value) !== -1
  }
}

您可以在 Vue 方法部分定义验证器方法。

类似这样的:

export default {
  props: {
    isSharedByOtherMember: {
      type: Boolean,
      default: false
    },
    archivedId: {
      type: String,
      default: null,
      required: false,
      validator: this.validateArchiveId(),
      errorMessage: 'Archived ID required when isSharedByOtherMember has value of true.'
    }
  },
  methods: {
    validateArchiveId () {
      return this.isSharedByOtherMember
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    • 2011-09-18
    • 2013-04-06
    • 1970-01-01
    • 1970-01-01
    • 2011-01-25
    相关资源
    最近更新 更多