如果在模板中使用变量获取错误未定义,则异步vuex获取操作状态已填充

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

我有一个异步动作vuex,我使用地图getter和组件创建函数来获取和填充数据,如果即时通讯使用此存储数据内联对象在模板视图控制台显示错误未定义,如果我尝试访问变量只有没有内联对象即时获取未定义错误对于内联对象,我认为这个关于异步函数的错误没有阻塞主进程组件完全加载和异步函数填充变量之后

行动,国家

 // state
   export const state = {
    app: null
   }

   // getters
   export const getters = {
    app: state => state.app,
   }

   // mutations
   export const mutations = {
   [types.FETCH_APP_SUCCESS] (state, { app }) {
     state.app = app
   },

   [types.FETCH_APP_FAILURE] (state) {
    state.app = null
   },

   [types.UPDATE_APP] (state, { app }) {
     state.app = app
   }
   }
 async fetchApp ({ commit }) {
 try {
  const { data } = await axios.get('/api/app/1')
  commit(types.FETCH_APP_SUCCESS, { app: data })
 } catch (e) {
  commit(types.FETCH_APP_FAILURE)
 }
}

零件

<template>
 <div>
   {{app.name}}
 </div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  middleware: 'auth',

created () {
  // i try here async and await
 this.$store.dispatch('app/fetchApp')
},

computed: mapGetters({
 app: 'app/app'
}),

metaInfo () {
 return { title: this.$t('home') }
}
}
</script>

国家充满enter image description here

变量可以在html enter image description here中看到

但控制此错误enter image description here

vue.js vuejs2 async-await vue-component vuex
1个回答
0
投票

app/app最初是null,你的模板没有null检查app.name,这导致你看到的错误。您可以在模板中使用conditionally render app.name

<template>
  <div>
    <template v-if="app">
      {{app.name}}
    </template>
  </div>
</template>

或者在商店中使用空字符串作为app/app的初始状态而不是null

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