Vue - 挂载前未及时计算数据

foo*_*opz 5 vue.js vuex

我正在学习 Vue,但遇到了一个问题,我的数据从计算方法返回未定义。似乎在安装组件时没有计算数据,可能是由于 get 请求 - 将 my 包装this.render()在 a 中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);
    },
}
Run Code Online (Sandbox Code Playgroud)

商店.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)
                })
        }
    }
})
Run Code Online (Sandbox Code Playgroud)

Max*_*nev 3

这是因为当 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();
       }
    }
}
Run Code Online (Sandbox Code Playgroud)

PS 并且不要使用render单词作为方法名称或其他东西,因为 Vue 实例具有render功能,并且可能会有点混乱。