【问题标题】:Access class method via Vue 3 + Vuex state + Typescript通过 Vue 3 + Vuex state + Typescript 访问类方法
【发布时间】:2021-10-19 00:46:34
【问题描述】:

是否可以通过 Vuex 状态访问类方法?

在以下情况下,我想调用fullName()来显示用户的格式化名称。

TypeError: store.state.user.fullName is not a function

类

export class User {
    constructor(
        public id: string = '',
        public first_name: string = '',
        public last_name: string = '',
    ) {}

    fullName = (format: 'forward' | 'reverse' = 'forward') => {
        if (format === 'forward') return `${this.first_name} ${this.last_name}`
        if (format === 'reverse') return `${this.last_name}, ${this.first_name}`
    }
}
export interface RootState {
    user: User
}

Vuex

export const key: InjectionKey<Store<RootState>> = Symbol()

export default createStore<RootState>({
    strict: true,
    state: {
        user: new User(),
    },
})

组件

setup(){
    const state = useState(key)
    return {
        name: computed(_ => store.state.user.fullName('forward'))
    }
}

【问题讨论】:

    标签: javascript typescript vue.js vuex vuejs3


    【解决方案1】:

    看起来,Vuex 剥离了类方法,只存储其普通值。

    我恢复类方法的解决方法是将 Vuex 用户状态复制到用户的新实例中。

    const user = computed(_ => Object.assign(new User(), store.state.user))
    

    【讨论】:

    • 我不确定它是否剥夺了他们,我不知道这种行为,并怀疑你做错了什么。课程出错了,您根本不应该使用它。 fullName 是没有充分理由的实例方法,并且被硬编码以在 this 上使用非反应性属性,检查 fullName = 糖语法的真正工作原理。
    猜你喜欢
    • 2021-07-08
    • 2021-02-26
    • 2019-05-23
    • 2021-07-08
    • 2021-03-12
    • 2021-07-02
    • 2021-07-01
    • 2019-12-28
    相关资源
    最近更新 更多