Vuex-从状态获取价值时的未定义属性

时间:2020-10-27 13:28:24

标签: vue.js vuex vuejs3

我是Vue JS的新手,在使用Vuex时,我遇到了一些问题。 我想要的是:更改作为一个对象的“用户”状态,并从“用户”状态在导航栏中显示“ userName”属性。我还在路由器/index.js文件中使用Vue Router,我正在提交状态更改。

我的store / index.js文件:

import { createStore } from 'vuex'

export default createStore({
  state: {
    user: null
  },

  mutations: {
    SET_USER(state, user){
      state.user = user
    }
  },

  actions: {
    setUser({commit}, user){
      commit('SET_USER', user)
    }
  },

  modules: {
  }
})

我的router / index.js文件:

import { createRouter, createWebHistory } from 'vue-router'
import users from '../assets/users'
import store from '../store'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  // I have 2 more routes
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach(async(to, from, next) => {
  const user = store.state.user
  if(!user){
    await store.dispatch('setUser', users[0]) // getting the first user object from assets/users.js
  }
  
})

export default router

我的UserProfile.vue文件:

<template>
  <div class="nav">
    <h3 id="logo"><router-link to="/">Twooter</router-link></h3>
    <h3 id="username">{{ user.userName }}</h3>
  </div>
</template>
<script>
import {reactive, computed} from 'vue'
import {useStore} from 'vuex'

export default {
    name: 'UserProfile',
    setup(){
        const store = useStore()
        
        // computed
        const user = computed(() => store.state.user)

        return {
            user
        }
    }
}
</script>

现在,当我在元素中调用{{user.userName}}时,我在控制台中收到以下错误和警告:

[Vue warn]: Unhandled error during execution of render function 
  at <UserProfile onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< undefined > > 
  at <RouterView> 
  at <App>
[Vue warn]: Unhandled error during execution of scheduler flush. This is likely a Vue internals bug. Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/vue-next 
  at <UserProfile onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< undefined > > 
  at <RouterView> 
  at <App>

UserProfile.vue?4a39:4 Uncaught (in promise) TypeError: Cannot read property 'userName' of undefined
    at Proxy.render (eval at ./node_modules/cac   ....... And many other stuffs.

我正在使用Vue版本^ 3.0.0和Vuex版本^ 4.0.0-beta.4。 根据官方文档,我已经使用“ npm install vuex @ next --save”命令安装了Vuex。

我们将不胜感激任何帮助。

0 个答案:

没有答案