如何在vue中以store.js的状态存储信息?

问题描述

我正在用vuejs开发我的第一个应用程序。 这是一个包含几个步骤的表单,这些表单共享一个页眉和一个页脚,并且随着我的前进,我将在每个部分中放入的信息发送到store.js。 我已经停留了几天,因为我无法从表单的第一部分中检索信息,从而无法显示在最后一步中输入的信息的摘要。 在每次单击高级按钮的每个步骤中,我都将信息发送到store.js,然后导航到下一个组件。 这将是其中一个组件中动作的示例

      onSubmit() {
             
        const formData = {
            selectedService: this.focusService,selectedItem: this.selectedItem,selectedShop: this.selectedShop,selectedItemId: this.selectedItemId
          };
          this.$store.dispatch('formInfo',{
            selectedService: formData.selectedService,selectedItem: formData.selectedItem,selectedShop: formData.selectedShop,selectedItemId: formData.selectedItemId            
          });
          this.$store.dispatch('setStep',this.step + 1)
          this.$router.push('/shop/buyer')

      },

在store.js中,我检查信息是否正确地通过“ formInfo()”方法到达,然后将其保存在声明的状态类属性中,并设置了存储在该状态中的信息。

export default new Vuex.Store({
  state: {
    step: 0,idToken: null,items: null,shops: null,estimations:null,owner: {
      ownerCivility: '',ownerLastname: '',ownerFirstname: '',ownerAddressFirstLine: '',ownerAddressSecondLine: '',ownerAddressthirdLine: '',ownerPostalCode: '',ownerCity: '',ownerPhone: '',ownerEmail: '',country: 'FR'
    },fisrtStepInfo: {

    }
  },actions: {
      formInfo({commit,dispatch},authData) {
      console.log(authData)
      this.fisrtStepInfo = authData
      console.log(this.fisrtStepInfo)
    }

  },getters: {
    formInfoFirstStep (state) {
      console.log(state)
      return state.fisrtStepInfo
    }
  }

最后,在我想在html中显示该信息的组件中,我在脚本的“计算”部分中设置了对先前在store.js中声明的getter的调用


    export default {
        data() {
            return {
              step: 2,civil: '',name: '',lastName: '',email: '',adresse: '',phone: '',postalCode: '',submitted: false,}
        },components:{
        },computed: {
            firstFormInfo() {
              console.log('firstforminfo')
              return !this.$store.getters.formInfoFirstStep
            },}
   }
</script>



但是在这一点上,它甚至还没有通过我的“计算”部分中的getter。

我在做什么错了?

提前感谢您的时间和帮助。

解决方法

动作与突变相似,不同之处在于:动作不是突变状态,而是突变。

您需要commit进行突变,而不是直接更改state

  state: {
    ...
    fisrtStepInfo: {}
  },mutations: {
    setStepInfo: (state,data) => state.fisrtStepInfo = data;
  }
  actions: {
    formInfo({commit,dispatch},authData) {
      console.log(authData)
      commit('setStepInfo',authData)
      console.log(this.fisrtStepInfo)
    }
  },getters: {
    formInfoFirstStep (state) {
      console.log(state)
      return state.fisrtStepInfo
    }
  }