【问题标题】:VueJS - Result of a function as default value for a PropVueJS - 函数的结果作为 Prop 的默认值
【发布时间】:2020-12-07 15:59:42
【问题描述】:

将 VueJS 与类组件和 vue-property-decorator 一起使用我正在尝试编写一个带有 uuid Prop 的 Vue 组件,该属性在未提供时默认为新的 uuid(使用 npm 包 uuid):

import {Component, Prop, Vue} from 'vue-property-decorator';
import * as uuid from 'uuid';

@Component
export default class BlockComponent extends Vue {
  @Prop({default: uuid.v1()}) uuid!: string;
}

这样当实例化时给出服务器提供的 uuid 时,它会在前端使用,如果不是,则意味着它是一个新元素,应该为该组件生成一个新的 uuid。这段代码的问题是我最终会产生多个组件,这些组件使用相同的uuid(但不是全部)。

【问题讨论】:

  • 使用函数()=> uuid.v1()
  • 太棒了!谢谢 !我不知道我可以传递一个返回字符串作为字符串属性默认值的函数。我最终这样做了:{default: uuid.v1} 它可以工作
  • @Estradiaz 愿意写一个简短的答案,以便我可以将其设置为已解决?

标签: vue.js uuid vue-props vue-class-components vue-property-decorator


【解决方案1】:

根据documentation,您可以使用构造函数,因此可以传递函数。

@Prop(options: (PropOptions | Constructor[] | Constructor) = {})

【讨论】:

    猜你喜欢
    • 2021-02-02
    • 1970-01-01
    • 2018-06-20
    • 2019-09-11
    • 2010-09-17
    • 2017-08-31
    • 2011-11-18
    • 2017-07-08
    相关资源
    最近更新 更多