【发布时间】:2021-04-09 12:36:52
【问题描述】:
我有一个包含 username 字符串的 Vuex 商店。它最初设置为空字符串,但每个用户,无论新旧,最初都会被分配一个随机字符串。
我想允许用户更改他们的用户名。我还想在文本输入中将用户名显示为初始 value。
但是,初始值只是一个空字符串。在创建的(或之后的任何生命周期方法)中记录username 时,我得到[__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
}
【问题讨论】:
-
这意味着
username在钩子运行后被异步设置。如果您的代码依赖于username的最新值,请在其上使用观察器来观察变化。
标签: typescript vue.js asynchronous vuejs2 vuex