typescript - Vuex 商店在 created() 方法中返回 [__ob__: Observer] 而不是字符串
问题描述
我有一个包含username
字符串的 Vuex 商店。它最初设置为空字符串,但每个新用户或旧用户最初都会被分配一个随机字符串。
我想允许用户更改他们的用户名。我还想value
在文本输入中将用户名显示为首字母。
但是,初始值只是一个空字符串。登录username
created (或之后的任何生命周期方法)时,我得到[__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
}
解决方案
[ 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: {}
});
推荐阅读
- javascript - 在 Javascript 的网格中显示图像
- css - 如何在 Prime React 中灰显动态菜单
- python - 使用 Sklearn 进行蛮力模型选择
- reactjs - 不变违规:可加载:SSR 需要 `@loadable/babel-plugin`,请安装它可加载组件
- java - 致命异常:java.lang.IllegalArgumentException fd 在仅 Android Q 的 PrintAdapter 类的 onwrite() 中不能为空
- java - 使用 jaxrs 对 java 后端应用程序进行单元测试,使用 jpql 进行 dao,在 glassfish 上运行
- rest - 如何获取自定义属性 AllowedValues 的 objectID 字段以更新/删除它们?
- nim-lang - Nim 中的排序列表应该使用什么类型?
- javascript - 如何通过修复任何潜在不匹配的步骤来增加/减少数字?
- php - 如何在 nginx 中通过单个 ip 配置多个 yii 应用程序?