首页 > 解决方案 > Vuex 商店在 created() 方法中返回 [__ob__: Observer] 而不是字符串

问题描述

我有一个包含username字符串的 Vuex 商店。它最初设置为空字符串,但每个新用户或旧用户最初都会被分配一个随机字符串。

我想允许用户更改他们的用户名。我还想value在文本输入中将用户名显示为首字母。

但是,初始值只是一个空字符串。登录usernamecreated (或之后的任何生命周期方法)时,我得到[__ob__: Observer]. 如果我将超时设置为 500 毫秒,我会得到预期的字符串,但这对我来说太乱了。

以下是相关代码:

<template>
  <form @submit.prevent>
    <input
      type="text"
      v-model="usernameField"
    />
    <button @click="usernameUpdate()">
      Submit
    </button>
  </form>
</template>

<script lang="ts">
  import { Vue, Component } from 'vue-property-decorator'
  import { namespace } from 'vuex-class'

  const AccountGetter = namespace('account').Getter
  const AccountAction = namespace('account').Action

  const AppProps = Vue.extend({
    data: () => {
      return {
        usernameField: ''
      }
    },
    created() {
      this.usernameField = this.username
      console.log(this.username)
      // returns [__ob__: Observer]
      // using setTimeout() works though
    },
    methods: {
      async usernameUpdate() {
        // working code using updateUserProfile
      }
    }
  })

  export default class VerifyGame extends AppProps {
    @AccountGetter username!: String;
    @AccountAction updateUserProfile
  }
</script>

Vuex商店:

// also includes updateUserProfile mutation

import { AccountState, RootState } from './types'
import { GetterTree } from 'vuex'

type AccountGetter = GetterTree<AccountState, RootState>

export const state: AccountState = {
  username: ''
}

export const getters: AccountGetter = {
  username: state => state.username
}

标签: typescriptvue.jsasynchronousvuejs2vuex

解决方案


[ ob : Observer] 是一个对象。您需要的值将在它下面的变量中。您可以使用 this.username.varname 获取所需的变量。

我建议你为你的 vuex 使用类似下面的东西。并使用 addUserData 突变来更新您的用户名。其中的数据可以通过 this.$store.state.userData.username 访问

export default new Vuex.Store({
    state: {
        userData: {
            username: ""
        }
    },
    getters: {},
    mutations: {
        addUserData(state, data) {
            // state.userData.assign(data)
            state.userData = Object.assign({}, data);
        }
    },
    actions: {}
});

推荐阅读