Yoshiki.N
Yoshiki.N

Reputation: 21

[Nuxt.js/Typescript]how to get data from vuex?

I'm a Typescript newbie. I set Objective Data to Vuex store, but I can't get it.

This is the Objective data of Users(in other words, account).

# models/User.ts

export interface IUser {
  email: string | null
  name: string | null
}

export class UserClass implements IUser {
  email: string | null
  name: string | null

  constructor(email: string | null, name: string | null) {
    this.email = email
    this.name = name
  }
}
# store/accounts.ts

import { UserClass } from '~/models/User'

@Module({ stateFactory: true, namespaced: true, name: 'account'})
export default class Account extends VuexModule {
  user: UserClass | null = null

  get currentUser() {
    return this.user
  }

  @Mutation
  storeUser(user: UserClass | null){
    this.user = user
  }

  @Action({})
  setUser(user: UserClass | null){
    this.storeUser(user)
  }
}
# utils/store-accessor.ts

import { Store } from 'vuex'
import { getModule } from 'vuex-module-decorators'
import Account from '~/store/account'

let accountStore: Account

function initializeStore(store: Store<any>): void {
  accountStore = getModule(Account, store))
}
export { initializeStore, accountStore }
# components/Sample.vue

<template>
  <div>
    <p>NAME: {{currentUser.email}}</p>    // ★error !
  </div>
</template>
export default class SampleCmp extends Vue {
  @Prop() currentUser: UserClass | null = accountStore.currentUser
}

I want to get email like above currentUser.email, but got error Cannot read property 'email' of null. If it set just currentUser, the stored data like {email: [email protected], name: dummy} is output to page as it is.

what should I do ? please help !

regards.

Upvotes: 2

Views: 3217

Answers (1)

Vektor88
Vektor88

Reputation: 4920

You can do it with the vuex-class library, which is already installed with nuxt-property-decorator.

When declaring your component, import also the namespace from nuxt-property-decorator:

import { Vue, Component, namespace } from 'nuxt-property-decorator'
const user = namespace('user')

Then you can access your user store properties like this using vuex-class decorators:

@user.Getter
public currentUser!: string


@user.Mutation
public storeUser!: (data: UserClass | null) => void

@user.Action
public setUser(user: UserClass | null) => void

You can find more on this topic in the vuex section of this article.

Alternatively, the official nuxt typescript documentation suggests to try the nuxt-typed-vuex package.

Upvotes: 1

Related Questions