【问题标题】:How to handle navigation when removing the current page's Vuex record?删除当前页面的 Vuex 记录时如何处理导航?
【发布时间】:2019-05-25 10:13:36
【问题描述】:

我有一个ClientManagePage,我在其中显示客户信息并允许删除显示的客户。

该页面的 vue-router 路由配置如下所示:

{
  path: '/client/:id/manage',
  name: 'client',
  component: ClientManagePage,
  props: ({ params }) => ({ id: params.id }),
}

客户端实体存储在 vuex 存储中。 ClientManagePage 使用 id 属性从商店获取其客户端实体,并显示客户端的各种属性和“删除”按钮。

移除按钮监听器是(在mapActions 内):

async removeClientClicked(dispatch) {
  // Wait for the action to complete before navigating to the client list
  // because otherwise the ClientListPage might fetch the client list before
  // this client is actually deleted on the backend and display it again.
  await dispatch('removeClientAction', this.id);
  this.$router.push({ name: 'clientList' });
},

移除一个客户端的 vuex 动作是:

async function removeClientAction({ commit }, id) {
  // Remove the client from the store first (optimistic removal)
  commit('removeClient', id);
  // Actually remove the client on the backend
  await api.remove('clients', id);
  // Moving "commit('removeClient', id);" here still produces the warning mentioned below
}

我的问题是如何在删除客户端时处理导航到另一条路线。当前代码在开发模式下会产生警告,例如:

[Vue warn]: Error in render: "TypeError: Cannot read property 'name' of undefined"

found in

---> <ClientManagePage> at src/pages/ClientManagePage.vue
       <Root>

这当然是由反应系统启动并尝试使用现已删除的 vuex 客户端实体更新页面内容引起的。这发生在 removeClientAction 完成之前,因此导航到 ClientList 页面。

我已经想出了一些可能的解决方案,但它们并不是很吸引人:

  • 在 ClientManagePage 顶部有一个 v-if="client",当客户端不存在于商店中时隐藏所有内容。
  • 使用 ClientManagePage 中的计算属性 client 返回包含页面所需属性的默认“虚拟”客户端。但在操作进行期间,该页面仍会闪烁“虚假”内容。
  • 在调度removeClientAction 之后(甚至之前)导航到“clientList”。这会导致 clientList 在操作完成时短暂显示已删除的客户端,这是不好的。

对于这个看似常见的在删除当前页面显示的底层vuex实体时导航离开的问题,还有其他解决方案吗?

【问题讨论】:

  • 您的视图/组件看起来如何?如果 store 没有默认值,也许可以使用 computed 设置一个默认值,那么当记录被删除时,你的视图就不会爆炸。
  • @Stuart 客户端有一个computed 属性,其他所有内容都从该属性派生。组件的其他部分具有像 {{ client.name }}{{ client.account.active }} 这样的插值,它们使用计算属性作为它们的根对象。我会将您的建议添加到问题中可能的解决方案列表中。

标签: vue.js vuejs2 vuex vue-router


【解决方案1】:

我最终在 ClientManagePage 的顶部做了一个很大的v-if,它隐藏了所有内容,而客户端不存在于商店中。它不漂亮,但它有效。改进可能是在v-else 中显示“请稍候,操作正在进行中”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-11
    • 1970-01-01
    相关资源
    最近更新 更多