Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

typescript - Vue Prop has no initializer and is not definitely assigned in the constructor

I am using props in Vue Class components. The props are defined in the constructor without a value. This compiles and works fine, but since the latest VS Code / TSLint update, I get the following warning:

Property 'tag' has no initializer and is not definitely assigned in the constructor.

Vue Class Component

export default class Browser extends Vue {
  @Prop({default: '', required:false})
  tag: string

  created(){
     console.log("the tag prop is " + this.tag)
  }
}

If I DO assign it, I get the Vue warning that you shouldn't manipulate a Prop in a child component.

[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders

Since this seems primarily a linting problem, is there a way to disable this? Or is my code actually wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You don't need set strictPropertyInitialization": false to solve this.

According to this link in Microsoft TypeScript-Vue-Starter repo:

Properties are defined by prefixing instance variables with the @Prop() decorator from the vue-property-decorator package. Because the --strictPropertyInitialization option is on, we need to tell TypeScript that Vue will initialize our properties by appending a ! to them. This tells TypeScript "hey, relax, someone else is going to assign this property a value."

You just need to append the ! to the prop name:

@Prop({default: '', required:false})
  tag!: string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...