【问题标题】:Vuex: How to grab latest user data after user profile updated?Vuex:用户资料更新后如何获取最新的用户数据?
【发布时间】:2020-06-01 11:10:57
【问题描述】:

我正在使用 Vuex,并且在用户的个人资料更新后无法让用户的数据“反应”。这是我的场景:

我的App.vuecreated() 挂钩期间检查用户的属性 像这样:

  async created() {
    await this.$store.dispatch('getSSOUser') // gets user from auth server
    await this.$store.dispatch('fetchUserProfiles') // queries known user table to see if user has a profile
    // set for global user state throughout app
    await this.setUser()
// then loads the UI
    this.isBusy = false
  methods: {
    setUser() {
      const user = this.getUserProfileBySSOID(this.ssoUser.data.user_id)
      this.$store.commit('SET_USER', user)
    }

所以现在我有了可以在整个应用程序中使用的用户个人资料(user 对象)。效果很好......但是......当用户在应用程序中编辑他的个人资料(例如,更新他的电话号码等)并点击提交时,我似乎无法让状态刷新/看到有除非用户手动刷新页面,否则会发生变化。

处理此问题的推荐方法是什么?我是否需要在每次路由更改时对用户状态进行调度?用户个人资料位于path: '/userEdit/:uid'

这是我的应用结构:

<div id="app">
    <Banner />
    <section class="container-fluid">
      <loading-spinner v-if="isBusy"></loading-spinner>
      <div v-else>
        <AuthName class="text-right" />
        <MainNav />
        <main id="routerView">
          <transition name="component-fade" mode="out-in">
            <RouterView :key="$route.fullPath" />
          </transition>
        </main>
      </div>
    </section>
  </div>

用户资料更新功能:

  ApiService.putUserProfile(this.user)
    .then(() => {
      this.loading = false
      this.$router.push('/admin/users')
      }
    })
    .catch(err => {
      if (err.response) {
        this.errors = err.response.data
      } else {
        if (err.request) {
          this.errors = err.request
        } else {
          this.errors = err.message
        }
      }
      this.loading = false
      console.error('Error from update', err)
    })

【问题讨论】:

  • 需要查看您的更新功能来回答这个问题。如果您获得了用户信息,那很好,但他们的信息被更改的方式一定有问题。您是为此发布到数据库还是只更新商店?
  • @Daniel_Knights:添加了更新功能。我发布到数据库谢谢!
  • 你能发帖ApiService吗?

标签: vue.js vuex


【解决方案1】:

更新用户的详细信息后,您可以触发一个事件,该事件可能会从后台服务器获取数据。

methods:{
loadData(){
         await this.$store.dispatch('getSSOUser') ;
         await this.$store.dispatch('fetchUserProfiles');
         await this.setUser()
         this.isBusy = false
          },
updateInfo() {
                this.form.put('api/profile').then((response) => {
                let userData = response.data.userdata;
                Fire.$emit('ProfileEvent');
            }
           },
  },
created(){
        this.loadData();
        Fire.$on('ProfileEvent', () => {
        this.loadData();
        });
       }

可能会在配置文件页面中保存任何更改后触发事件,并在触发事件后执行创建组件时调用的函数可能会解决您的问题。希望你能从上面的代码示例中得到启发。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-23
    • 2021-08-05
    • 2019-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多