【问题标题】:Nuxt.js nested route loading issueNuxt.js 嵌套路由加载问题
【发布时间】:2021-01-02 03:11:36
【问题描述】:

以上所有代码均来自我在 pages/apibuilder/models 文件夹中的文件 _id.vue

我用它来用数据填充我的商店

async asyncData({ store }) {
    // this.datas = await this.$axios
    //  .$get('/api/apibuilder/retrievemodel')
    //  .then(function (res) {
    //      return res
    //  })
    return { datas: await store.dispatch('apibuilder/retrieve_model') }
},

我在模板中以两种不同的方式使用这些数据

v-for 循环中的 1 个

<tr v-for="(data, name, index) in $store.state.apibuilder.currentModel.attributes":key="index">

2 我想显示这个 $store.state.apibuilder.currentModel.attributes 的编号 我是这样做的

<span> {{Object.keys($store.state.apibuilder.currentModel.attributes).length}}Champs</span>

如果我使用 nuxtlink 导航到我的嵌套页面:http://localhost:3000/apibuilder/models/Article 一切正常,我的循环和计数工作

但如果我尝试刷新页面或直接从 url 访问网站

我让循环工作,但不是计数 我有一个错误告诉我 $store.state.apibuilder.currentModel.attributes 为 null 并且它破坏了 object.keys().length

代码 1 和 2 在模板中非常接近,但它一次为 Null,并在几行后显示循环。

有什么想法吗?

ps,

我尝试在计算属性中进行计数,但它是相同的,当我重新加载页面时数据未定义。

我也尝试了 SSR = true 和 SSR = false

我也尝试过使用 fetch 而不是 asyncData

【问题讨论】:

    标签: javascript vue.js nuxt.js


    【解决方案1】:

    我认为问题与 fetch 或 asyncData 无关。

    您获取数据并将其存储在状态中。那挺好的。但在那之后,你不应该使用 store.state :改用吸气剂(我发现使用 mapGetters 更干净)。

    您的商店会很受欢迎:

    export const state = () => ({
        apibuilder: {},
    });
    export const getters = {
        attributes(state) {
            return state.apibuilder.currentModel.attributes;
        }
    }
    

    在你的组件中:

    import {mapGetters} from 'vuex';
    
    export default {
        computed: {
            ...mapGetters({
                attributes: 'attributes',
            }),
            countAttributes() {
                if (this.attributes) {
                   return Object.keys(this.attributes).length
                }
            }
        }
    }
    

    多亏了它,它会对商店中数据的变化做出反应。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-18
      • 2020-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-22
      • 2019-01-06
      相关资源
      最近更新 更多