【发布时间】: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?你在哪里定义的?