【问题标题】:What access modifiers should I use for the class-component in Vue?我应该为 Vue 中的类组件使用哪些访问修饰符?
【发布时间】:2019-08-15 19:09:44
【问题描述】:

我想知道应该为 Vue 类中的属性和方法使用哪些修饰符? (我使用vue-class-component 包)。 public, private, protected?

或者我应该关闭说我需要设置访问修饰符的 linter 规则吗?

这是一个示例组件:

@Component({
  components: { MyChildComponent }
})
export default class MyComponent extends Vue {
  // props
  @Prop({ type: String, default: '' }) public readonly value!: string
  @Prop({ type: Array, default: () => [] }) public readonly myProp1!: any
  @Prop({ 
    type: [Array, Object], 
    default: () => ({}) 
  }) public readonly myProp2!: any

  // data variables
  public myVar1: MyClass | null = null
  public myVar2: boolean = false

  // computed
  public get isDisabled (): boolean {
    // code...
  }

  // watch
  @Watch('value')
  public onValueChange (val) {
    // code...
  }

  // hook
  public mounted () {
    // code...
  }

  // method
  public setMenuItem () {
    // code...
  }
}

【问题讨论】:

标签: typescript vue.js vuejs2 vue-component vue-class-components


【解决方案1】:

Public:您可以从任何类访问属性或方法。

受保护:您可以访问同一类或任何子类中的属性或方法

私有:您可以在同一个类中访问属性或方法,但不能在该类之外访问。

参考here

使用public 通常没问题,只要您不关心其他组件是否修改该值或调用该函数。我会默认使用public,然后在必要时将其替换为privateprotected

关闭 linter 也可以,但是如果您在组件之间遇到问题并且您没有为组件之间使用的属性或方法定义访问修饰符,那么调试可能会很麻烦。

【讨论】:

  • 这个答案与 Vue 类/Vue 组件无关。这只是访问修饰符的一般解释。
  • 尽管这个问题与 Vue 组件有关,但这个问题的基本点是了解每种类型的访问修饰符何时合适。
猜你喜欢
  • 1970-01-01
  • 2016-05-17
  • 2018-04-18
  • 1970-01-01
  • 1970-01-01
  • 2021-09-18
  • 1970-01-01
  • 1970-01-01
  • 2021-10-09
相关资源
最近更新 更多