What access modifiers should I use for the class-component in Vue?
Asked Answered
F

1

8

I'm wondering what modifiers should I use for properties and methods in Vue classes? (I use vue-class-component package). public, private, protected?

Or should I turn off the linter rule that says I need to set an access modifier?

Here is an example component:

@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...
  }
}
Foppery answered 25/3, 2019 at 14:1 Comment(2)
You can turn the linter rule off and do not specify any for class members. The will be public by default typescriptlang.org/docs/handbook/classes.html#public-by-defaultStricker
@Pvl That's exactly what I did: "member-access": [true, "no-public"] for TSLintCleat
A
0

Public: You can access the property or method from any class.

Protected: You can access the property or method within the same class or any child classes

Private: You can access the property or method within the same class, but not outside of that class.

See here for reference.

Using public is usually fine as long as you don't care whether another component modifies that value or calls that function. I would just use public by default and then replace it with private or protected when necessary.

Turning off the linter works as well, but if you run into issues between components and you haven't defined access modifiers for properties or methods that are used between the components, it can be a nuisance to debug.

Angi answered 21/10, 2021 at 3:56 Comment(2)
This answer bears no relation to Vue classes/ Vue components. It is just a general explanation of access modifiers.Hudspeth
Even though the question relates to Vue components, the underlying point of this question is to understand when each type of access modifier is appropriate.Angi

© 2022 - 2024 — McMap. All rights reserved.