我有一个add-user.vue的部件.这是我添加新用户和编辑现有用户的模板.所以在页面加载时,我判断路由是否有id,如果有,我从状态数组中加载一个用户来编辑它.我的问题是user是未定义的,因为状态数组users是空的.如何确保我的用户对象没有未定义.它有时会加载,但刷新时不会.我以为我已经覆盖了它,但没有.这是我的设置.我错过了什么?

store

state: {
  users: []
},

getters: {
  users: state =>
    _.keyBy(state.users.filter(user => user.deleted === false), 'id')
},

actions: {
  fetchUsers({
    commit
  }) {
    axios
      .get('http://localhost:3000/users')
      .then(response => {
        commit('setUsers', response.data);
      })
      .catch(error => {
        console.log('error:', error);
      });
  }
}

在我的add-user.vue部分中,我在data() computed:{}created()中有以下内容

data() {
  return {
    user: {
      id: undefined,
      name: undefined,
      gender: undefined
    }
  };
},

computed: {
  ...mapGetters(['users'])
},

created() {
  if (this.$route.params.userId === undefined) {
    this.user.id = uuid();
    ...
  } else {
    this.user = this.users[this.$route.params.userId];
  }
}

模板

<template>
  <div class="add-user" v-if="user"></div>
</template>

在我的设置中,我有User.vue个用户

<template>
  <main class="main">
    <AddUser/>
    <UserList/>
  </main>
</template>

<script>
import AddUser from '@/components/add-user.vue';
import UserList from '@/components/user-list.vue';

export default {
    name: 'User',

    components: {
        AddUser,
        UserList
    },

    created() {
        this.$store.dispatch('fetchUsers');
    }
};
</script>

我试过这个.在我的编辑器中保存时,它会工作,但不会刷新.dispatch().then()先于用户设置的mutation运行

created() {
  if (this.$route.params.userId === undefined) {
    this.user.id = uuid();
    ...
  } else {
    if (this.users.length > 0) {
                this.user = this.users[this.$route.params.userId];
            } else {
                this.$store.dispatch('fetchUsers').then(() => {
                    this.user = this.users[this.$route.params.userId];
                });
            }
  }
}

推荐答案

对于这个特殊的 case ,它只是在同一个vue实例中来回切换.通过增加:key="some-unique-key"解决了这个问题,所以看起来是这样的.

<template>
  <main class="main">

    <AddUser :key="$route.params.userId"/>

    <UserList/>

  </main>
</template>

Vue.js相关问答推荐

如何在Vue 3中将动态特性从主零部件同步到子零部件

在预渲染模式下部署 nuxt 3 时出错

Vue composition api: 访问