【问题标题】:Vue - Data not computed in time before mountVue - 安装前未及时计算数据
【发布时间】:2019-01-05 07:59:21
【问题描述】:

我正在学习 Vue,但遇到了一个问题,即我的数据从计算方法返回未定义。似乎在安装组件时未计算数据,可能是由于获取请求 - 将我的 this.render() 包装在 setTimeout 中会正确返回数据。设置超时显然是不明智的,那么我应该如何做到这一点以获得最佳实践?

主页.vue

export default {
    created() {
        this.$store.dispatch('retrievePost')
    },
    computed: {
        posts() {
            return this.$store.getters.getPosts
        }
    },
    methods: {
        render() {
            console.log(this.comments)
        }
    },
    mounted() {
        setTimeout(() => {
            this.render()
        }, 2000);
    },
}

store.js

export const store = new Vuex.Store({
    state: {
        posts: []
    },
    getters: {
        getPosts (state) {
            return state.posts
        }
    },
    mutations: {
        retrievePosts (state, comments) {
            state.posts = posts
        }
    },
    actions: {
        retrievePosts (context) {
            axios.defaults.headers.common['Authorization'] = 'Bearer ' + context.state.token

            axios.get('/posts')
                .then(response => {
                    context.commit('retrievePosts', response.data)
                })
                .catch(error => {
                    console.log(error)
                })
        }
    }
})

【问题讨论】:

  • 在 render() 函数中,您试图控制 this.cmets?你在哪里定义的?

标签: vue.js vuex


【解决方案1】:

这是因为在Vue调用mounted hook时,axios请求还在处理中(这些动作是相互独立的),所以state.posts如预期的那样未定义。

如果您想在帖子加载时执行某些操作,请使用 watch 或更好的 computed(如果可能):

export default {
    created() {
        this.$store.dispatch('retrievePost')
    },
    computed: {
        posts() {
            return this.$store.getters.getPosts
        }
    },
    methods: {
        render() {
            console.log(this.comments)
        }
    },
    watch: {
       posts() { // or comments I dont see comments definition in vue object
           this.render();
       }
    }
}

附:并且不要使用 render 这个词作为方法名或其他东西,因为 Vue 实例有 render 函数,这可能会有点混乱。

【讨论】:

  • 感谢您抽出宝贵时间回复,这就是我想做的。
猜你喜欢
  • 1970-01-01
  • 2019-06-16
  • 2021-05-20
  • 2021-06-17
  • 2021-12-22
  • 2018-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多