typescript - Vue 3 中的 props 在基於類的組件中無法訪問
我正在遷移到 Vue 3。我無法在我的類中訪問 props 的值,反而它給我 0,而且在控制台中不會打印我在 prop 上使用的最新值。在模板中它工作正常,但我想在我的類中獲取 titleComponent 的最新值。
import { Options, Vue } from "vue-class-component";
@Options({
props: {
titleComponent: Number
}
})
export default class StorePin extends Vue {
private titleComponent = 0;
mounted()
{
console.log(this.propValue);
}
get propValue()
{
return this.titleComponent;
}
incremnt()
{
this.titleComponent ++ ;
}
}
答案#1
建立一個 Props 類別,在其中宣告你的 props,然後使用 .with() 方法將它加入到元件中!這將為你提供極佳的 TypeScript 支援,而且你甚至不需要使用 “@vue/runtime-core” 庫中的 PropType 介面。
<template>
<p>Hello world</p>
</template>
<script lang="ts">
import { Vue, Options, prop } from 'vue-class-component';
class Props {
array: string[] = prop({
required: true,
});
}
@Options({})
export default class MyComponent extends Vue.with(Props) {
}
</script>
<style lang="scss" scoped>
</style>
答案#2
屬性應該是唯讀的,所以如果你想在你的組件中修改 titleComponent,你需要修改本地副本(例如,來自監聽器):
import { Options, Vue } from "vue-class-component";
@Options({
props: {
titleComponent: Number
},
watch: {
titleComponent(val) {
this._titleComponent = val;
}
}
})
export default class StorePin extends Vue {
private _titleComponent = 0;
get propValue()
{
return this._titleComponent;
}
increment()
{
this._titleComponent++;
}
}
