gpt4 book ai didi

typescript - Vue 2 + typescript : Avoid mutating Prop directly - in a class based component with vue-property-decorator

转载 作者:搜寻专家 更新时间:2023-10-30 21:45:23 25 4
gpt4 key购买 nike

我希望能够在基于类的组件中使用 vue-property-decorator 声明我的 Prop,而无需初始化属性。

我被逼到墙角了:

  1. 如果我不初始化,TypeScript 就不会编译:

"TS2564 (TS) Property 'parentData' has no initializer and is not definitely assigned in the constructor."

  1. 如果我进行初始化,VueJS 会在运行时抛出警告:

"Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders."

下面的内容有效,但警告很烦人,也让我觉得有更好的方法:

import Vue from 'vue';
import { Component, Prop } from 'vue-property-decorator';
import { Client } from '../../../../domainmodels/client';

@Component({})
export default class SearchLocationsComponent extends Vue {

@Prop()
parentData: Client = new Client();

}


My dependencies:
"devDependencies": {
"@types/webpack-env": "^1.13.0",
"aspnet-webpack": "^2.0.1",
"awesome-typescript-loader": "^3.0.0",
"css-loader": "^0.25.0",
"event-source-polyfill": "^0.0.7",
"extract-text-webpack-plugin": "^2.0.0-rc",
"file-loader": "^0.9.0",
"style-loader": "^0.13.1",
"typescript": "^2.2.1",
"url-loader": "^0.5.7",
"vue": "^2.2.2",
"vue-loader": "^11.1.4",
"vue-property-decorator": "^5.0.1",
"vue-router": "^2.3.0",
"vue-template-compiler": "^2.2.2",
"webpack": "^2.2.0",
"webpack-cli": "^3.3.2",
"webpack-hot-middleware": "^2.12.2"
}

最佳答案

如果您没有在构造阶段初始化一个属性,您应该明确指出它可能是未定义的:

parentData: Client | undefined;

要为 @Prop 装饰成员分配默认值,您应该使用装饰器的 default 参数:

@Prop({ default: () => new Client}) 
parentData: Client | undefined;

或者,作为不推荐选项,您可以将"strictPropertyInitialization": false 添加到您的 typescript 编译器选项中。

更新 1:

最适合这种情况的解决方法是使用 definite assignment assertion modifiers,在 typescript 2.7 中引入。将它与默认的 Prop 装饰器初始化结合起来应该可以解决问题:

@Prop({ default: () => new Client }) 
parentData!: Client;

关于typescript - Vue 2 + typescript : Avoid mutating Prop directly - in a class based component with vue-property-decorator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56181197/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com