简体   繁体   English

Vue 组件无法读取异步 state 更改

[英]Vue component can't read async state change

I have a Vue component for a web shop checkout page where I want to call a function to populate billing address information inputs based on User profile data.我有一个用于 web 商店结帐页面的 Vue 组件,我想在其中调用 function 以根据用户配置文件数据填充帐单地址信息输入。 The User profile information is loaded from an API.用户配置文件信息从 API 加载。 This call is asynchronous and done using a Vuex action dispatch from the app index.js file.此调用是异步的,并使用应用程序 index.js 文件中的Vuex操作调度完成。 (We use user profile information elsewhere too, not just checkout page) (我们也在其他地方使用用户个人资料信息,而不仅仅是结帐页面)

Basically what keeps happening is the component mounts at the same time as when the store state gets populated with user data.I am unable to actually trigger a function based on when the state updates because the component cannot detect when this data is available to it.基本上,当存储 state 填充用户数据时,组件安装在同一时间发生。我无法根据 Z9ED39E2EA931586B6A985A6942EF57 何时更新此组件无法检测到此数据何时更新。 How can I make the component either detect when the data is available, or wait for it?如何使组件检测数据何时可用或等待它?

I don't want to bind inputs to the state, because I have multiple addresses and the user gets to pick whatever he likes.我不想将输入绑定到 state,因为我有多个地址,用户可以选择他喜欢的任何内容。 The address information from the inputs then have to be sent to the API so that they can be saved for the order.然后必须将来自输入的地址信息发送到 API,以便为订单保存它们。 So I'd rather have it on the component data:所以我宁愿把它放在组件数据上:

data (): IState {
  return {
    delivery_address: {
      name: '',
      streetAddress: '',
      postalCode: '',
      city: '',
      country: ''
    },
    billing_address: {
      name: '',
      streetAddress: '',
      postalCode: '',
      city: '',
      country: ''
    }
  }
}

What I've tried to do is have a computed user function that return state:我试图做的是让计算用户 function 返回 state:

user (): any {
    return this.$store.state.user
 }

I have tried setting watches to this:我尝试将手表设置为:

watch: {
    user (newUser, oldUser) {
      console.log(newUser)
    }
}

I have tried setting store watch我试过设置商店手表

mounted(): {
   this.$store.watch((state) => state.user,
    (user: any) => {
    console.log(user)
  })
  }
}

None of these methods actually help do anything to tell me that the user profile data is available.这些方法实际上都没有帮助告诉我用户配置文件数据可用。 What is the correct way to go about this? go 关于这个的正确方法是什么?

Vuex actions return promises, so you can add a .then() to the actions call to know when it is complete: Vuex 操作返回承诺,因此您可以在操作调用中添加.then()以了解它何时完成:

mounted() {
  this.$store.dispatch('loadUser').then(() => {
    // Update component state here
    console.log('User loaded: ', this.$store.state.user);
    this.delivery_address = this.$store.state.user.delivery_address;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM