Solve the data invalidation of uni app after using vuex to refresh

The data of vuex can be updated in response, but the refresh data will fail.
Cached data will not be lost after refresh, but will not be updated in response.
So we can use the combination of advantages and disadvantages to solve the data loss after the vuex refresh

Train of thought:
When storing the vuex data, it is stored in the cache by the way, and then the cache is obtained when the application is refreshed and stored in the vuex, so that the combination of cache and vuex can facilitate the project data storage

1. Set cache when storing data into vuex

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        hasLogin: false,
        userinfo: {},
    },
    mutations: {
        // Sign in
        login(state,res) {
            state.hasLogin = true
            state.userinfo = res
            uni.setStorage({
                key: 'userinfo',
                data: res
            })
            console.log(state.userinfo)
            console.log(state.hasLogin)
        }
    }
})

export default store

2. Call the vuex method to save data when obtaining user information

getUserData() {
        uni.request({
            url: this.apiUrl + 'small/index/indexme', 
            data: {
                openid: uni.getStorageSync('openid')
            },
            method: 'POST',
            success: (res) => {
                if(res.data.status == 1) {
                    console.log(res.data)
                    store.commit('login', res.data.user) // The method of vuex
                } else {
                    uni.showToast({
                        title: res.data.msg,
                        duration: 2000
                    })
                }
            }
        })
    },

3. Get the cache and store it in the vuex when the application is refreshed

<script>
    import { mapState, mapMutations} from 'vuex'
    export default {
        onLaunch: function() {
            console.log('App Launch')
            let openid = uni.getStorageSync('userinfo').openid // Judge whether there is an openid. If there is one, it means that you have logged in and re stored the cache in vuex
            if (openid) {
                uni.getStorage({
                    key: 'userinfo',
                    success: (res) => {
                        this.login(res.data)
                    }
                })
            }
        },
        onShow: function() {
            console.log('App Show')
        },
        onHide: function() {
            console.log('App Hide')
        },
        methods: {
            ...mapMutations(['login']),
        }
    }
</script>

<style>
    /*Public css per page */
    @import url("./static/iconfont/iconfont.css");
html {
    background-color: #f5f5fd;
}
</style>

In this way, the data of vuex will not be invalidated

Tags: Javascript Vue

Posted on Sat, 02 Nov 2019 05:30:58 -0700 by yurko