store.js
import api from '../../api/program' const state = { program: { list: [], detail: {} } } // detail 模拟数据 // detail = {title: '', desc: '', content: '', created: '', updated: ''} const getters = { detail: state => state.program.detail } const mutations = { GET_PROGRAM_DETAIL (state, res) { state.program.detail = res } } const actions = { getProgramDetail( { commit } ) { api.getProgramDetail(res => { commit('GET_PROGRAM_DETAIL', res) }) } } export default { state, getters, mutations, actions }
Program/detial.vue
<template>省略。。。</template> <script> import { mapGetters } from 'vuex' export.default { data() { return { 省略。。。 } }, watch: { detail() { this.handleInit() } }, computed: { ...mapGetters(['detail']), }, mounted () { const self = this; // 正常加载,这里可以输出detail数据,浏览器刷新就不行,必须通过watch监听来实现回调 console.log(self.detail.title) self.handleInit() }, methods: { handleInit() { const self = this // 正常加载和浏览器刷新后都可以实现 console.log(self.detail.title) }, } } <script> <style scoped>省略。。。</style>
总结: 首次打开页面时,mounted可以通过mapGetters实时获取detail数据,但通过浏览器强制刷新时,由于detail数据是通过api接口异步回调的,所以mounted此时输出是拿不到detail数据,而是直接输出undefind,因此通过watch监听detail变化来回调实现。