【问题标题】:set dynamic computed property in decorator VueJs Typescript在装饰器VueJs Typescript中设置动态计算属性
【发布时间】:2021-01-14 12:50:11
【问题描述】:

我有一个如下所示的组件:

@Component({
    computed: {
        [this.stateModel]: {
            get() {
                return this.$store[this.stateModel];
            }
        }
    }
})
class Component extends Vue{
    @Prop({ default: '' }) private stateModel!: string;
}

当我使用这个组件时,我正在尝试将stateModel 绑定为属性。 stateModel 应该是状态中的一个字段,可以注入到组件中。打字稿给我一个错误,上面写着:

元素隐式具有“any”类型,因为类型“typeof globalThis”没有索引签名。

我尝试创建一个接口并将其设置为计算,但它不起作用。

任何帮助都非常感谢。

【问题讨论】:

  • 如果 stateModel 是一个道具,当 stateModel 道具发生变化时,您是否尝试使用 store 中的值更新 stateModel 的值?
  • 嗨@Tony,我要做的是注入一个状态的名称属性stateModel
  • 观察者为你工作了吗?
  • @Tony 不,它没有。 stateModel 不是属性,它应该是动态的。我的意思是,如果我使用<Component :stateModel="foo">,则 foo 应该处于状态。

标签: typescript vue.js


【解决方案1】:

我尝试在计算属性中使用 this 关键字,但出现两个错误。

'this' 不能在计算属性名称中引用

'this' 隐含类型'any',因为它没有类型注释

或者,您可以使用观察者代替

import { Watch } from 'vue-property-decorator';

@Component
class Component extends Vue{
    ...

    @Watch('stateModel')
    stateModelHasChanged(newValue: number) {
      this.stateModel = this.$store[this.stateModel];
    }
    ...

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-29
    • 2021-01-13
    • 2019-05-11
    • 1970-01-01
    • 2018-12-13
    • 1970-01-01
    • 2021-06-25
    • 2020-06-20
    相关资源
    最近更新 更多