简体   繁体   English

设置 Vuex 数据之前的 Vue 组件加载

[英]Vue Component Loading Before Vuex Data Is Set

I have a Vue2 component that relies on Vuex to retrieve the currently selected node (infoNode) in order to show that node's data to the user.我有一个 Vue2 组件,它依赖于 Vuex 来检索当前选定的节点 (infoNode),以便向用户显示该节点的数据。 I have a beforeCreate function that uses Axios to retrieve the top level nodes and set the 'infoNode' as the first node as shown below:我有一个 beforeCreate function,它使用 Axios 检索顶级节点并将“infoNode”设置为第一个节点,如下所示:

  async beforeCreate(){
    const info = await axios.get('/ajax/company-info')
    if(info.data){
      this.$store.dispatch("setCompanyInfo", info.data)
    }

// Function to retrieve top level node
    const topLevel = await axios.get('/ajax/get-root-contents')
    if(topLevel.data){
      this.$store.dispatch("loadTopLevel", topLevel.data)
    }
  },

Below is the Vuex function to set the infoNode下面是设置infoNode的Vuex function

loadTopLevel(state,node){
      state.infoNode = node
    },

Here is where I try to grab the infoNode data and display an icon from an array of valid icons这是我尝试获取 infoNode 数据并显示来自有效图标数组的图标的地方

<v-icon size="6em" v-if="fileIcons[infoNode.data.filetype]">{{ fileIcons[infoNode.data.filetype] }}</v-icon>

Now, in my component, I have a computed prop that retrieves this infoNode from the store for display.现在,在我的组件中,我有一个计算道具,它从商店中检索这个 infoNode 以供显示。 The issue that I'm having is that the frontend is throwing an error stating 'e.infoNode.Data' is undefined'.我遇到的问题是前端抛出错误,指出“e.infoNode.Data”未定义。

This error is being thrown before the request is completed.在请求完成之前抛出此错误。 After the request completes, the frontend successfully displays the infoNode since the store is updated.请求完成后,由于商店已更新,前端成功显示了 infoNode。

Is there a way for me to set this data in the store before the component attempts to grab it?有没有办法让我在组件尝试获取数据之前在商店中设置这些数据? I've tried a lot of variations of beforeCreate (async and non) as well as created/mounted.我已经尝试了很多 beforeCreate 的变体(异步和非)以及创建/安装。

In your case beforeCreate() is async so the component renders before you set data to store.在您的情况下, beforeCreate() 是异步的,因此组件在您设置要存储的数据之前呈现。 You're displaying v-icon if fileIcons have specific entry ( infoNode.data.filetype ), but at that moment infoNode is undefined or infoNode.data is undefined.如果fileIcons具有特定条目( infoNode.data.filetype ),则显示v-icon ,但此时infoNode undefinedinfoNode.data未定义。

In v-if you should check if infoNode is not undefined and has entry you're searching for.v-if 中,您应该检查infoNode是否未定义并且是否具有您正在搜索的条目。

Something like this:是这样的:

computed: {
  hasEntry() {
    if(infoNode && ('data' in infoNode)) return true

    return false
  }
}

//template
<v-icon size="6em" v-if="hasEntry">{{ fileIcons[infoNode.data.filetype] }}</v-icon>

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

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