为什么新添加的数据没有反映在primevue的table组件中?

问题描述 投票:0回答:1

我正在尝试创建一个费用跟踪器,超级用户可以在其中创建用户帐户,并将其数据存储在 pinia 存储中。表组件应检测用户帐户数组中的更改并反映此表中新添加的用户。

我是 vue3 和 pinia 的新手。

文件:store.js

import { defineStore } from 'pinia'
import { computed, ref, reactive } from 'vue'

export const Store = defineStore('finance', () => {
  const getDate = () => {
    const currentDate = new Date()
    return currentDate.toLocaleString('en-US', {
      month: 'short',
      day: 'numeric',
      year: 'numeric',
      hour: 'numeric',
      minute: 'numeric',
      second: 'numeric'
    })
  }

  const superUser = { email: '[email protected]', secret: 'Munich' }

  let userIdCount = 1
  const userAccounts = ref([
    {
      accountID: userIdCount++,
      accountName: 'Veer',
      balance: 250,
      created: getDate(),
      updated: '-'
    }
  ])

  const savingsHistory = ref([])
  const expenseHistory = ref([])
  // const stateAccount = reactive({
  //   userAccount: [
  //     {
  //       accountID: userIdCount++,
  //       accountName: 'Veer',
  //       balance: 250,
  //       created: getDate(),
  //       updated: '-'
  //     }
  //   ],
  //   savingsHistory: [],
  //   expenseHistory: []
  // })

  const addUser = (name, initialBalance) => {
    const userDetail = {
      accountID: userIdCount++,
      accountName: name,
      balance: initialBalance,
      created: getDate(),
      updated: '-'
    }
    console.log(userDetail)

    userAccounts.value.push(userDetail)
    console.log(`Array after: ${userAccounts.value}`)
  }

  const updateSaving = (id, saving) => {
    const account = userAccounts.value.find((acc) => acc.accountID === id)
    if (account) {
      account.updated = getDate()
      account.balance += saving
      console.log(`Savings Before Update: ${savingsHistory.value}`)

      savingsHistory.value.push({
        user: account.accountName,
        savings: saving,
        updated: account.updated
      })
      console.log(`Savings Updated: ${savingsHistory.value}`)
    }
  }

  const updateExpense = (id, expense) => {
    const account = userAccounts.value.find((acc) => acc.accountID === id)
    if (account && account.balance >= expense) {
      account.updated = getDate()
      account.balance -= expense
      expenseHistory.value.push({
        user: account.accountName,
        expense: expense,
        updated: account.updated
      })
      return true
    }
    return false
  }

  const state = reactive({
    showAccountFormStatus: false,
    showSavingsFormStatus: false,
    showExpenseFormStatus: false
  })

  const toggleAccountForm = () => (state.showAccountFormStatus = !state.showAccountFormStatus)
  const toggleSavingsForm = () => (state.showSavingsFormStatus = !state.showSavingsFormStatus)
  const toggleExpenseForm = () => (state.showExpenseFormStatus = !state.showExpenseFormStatus)

  const getFullName = computed(() => superUser.email.split('@')[0])
  const getUserAccounts = computed(() => [...userAccounts.value])

  return {
    superUser,
    getFullName,
    toggleAccountForm,
    toggleSavingsForm,
    toggleExpenseForm,
    addUser,
    state,
    userAccounts,
    savingsHistory,
    expenseHistory,
    updateSaving,
    updateExpense,
    getUserAccounts
  }
})

文件:TableComponent.vue

<script setup>
import DataTable from 'primevue/datatable'
import Column from 'primevue/column'
import { Store } from '@/stores/store'

import { computed, nextTick } from 'vue'

// Initialize the store
const store = Store()

// // Access the user accounts directly from stateAccount

// console.log(userAccounts)

const userAccounts = computed(() => store.getUserAccounts)

console.log(userAccounts.value)

nextTick(() => {
  console.log('User Accounts:', userAccounts.value)
})

// console.log(userAccounts)
</script>

<template>
  <DataTable :value="userAccounts" showGridlines responsiveLayout="scroll">
    <Column field="accountID" header="Account-ID"></Column>
    <Column field="accountName" header="Account User"></Column>
    <Column field="balance" header="Balance"></Column>
    <Column field="created" header="Created-On"></Column>
    <Column field="updated" header="Updated-On"></Column>
  </DataTable>
</template>

为什么它没有按预期工作?

需要一些清晰解释的帮助。

javascript vuejs3 store pinia primevue
1个回答
0
投票

我认为您使用的语法不适用于您所描述的 pinia,特别是因为 pinia 已经具有处理突变的属性,并且您使用的声明与 vanilla vue 相关。

但与您的问题相关,发生的情况是,在您的商店中,您已经将

getUserAccounts
定义为
computed
属性,当您在
TableComponent.vue
中检索它时,您将再次将其作为
computed 传递
.

我希望在您的商店中遵循以下语法:

Store.js

import { defineStore } from 'pinia';

export const useCounterStore = defineStore('counter', {
  state: () => ({
    // ...all mutable properties here
    counter: 0,
  }),
  getters: {
    // ... All getters properties here
    doubleCount: (state) => state.counter * 2,
  },
  actions: {
    increment() {
      this.counter++;
    },
  },
});

###MockComponent.vue:

import { useCounterStore } from '../store/location';

const userStore = useCounterStore();

console.log(userStore.count)
userStore.count += 1
console.log(userStore.count)

console.log(userStore.doubleCount)
userStore.increment()
console.log(userStore.count)

以下是定义商店时应注意的 pinia 的一些核心概念:https://pinia.vuejs.org/core-concepts/

© www.soinside.com 2019 - 2024. All rights reserved.