当您检测到用户不再登录或未通过身份验证时,您可以将商店中的 username 设置为 ''。
关于我的评论,这里有一些代码可以看。
您是否正在做任何可以绑定的身份验证?我以前通过实现身份验证并在用户未经身份验证时删除 cookie/缓存的登录数据来处理过类似的事情。在我们的一个项目中,我们创建了一个 auth.js 存储模块来处理身份验证。
我知道这并不能直接回答您关于在设定时间后自动从商店中删除某些东西的问题。但它应该在 cookie 过期或被删除时清除存储的值。不过还没有测试。
主应用/调用商店模块
const store = new Vuex.Store({
modules: {
auth
}
})
new Vue({
el: '#app',
store,
render: h => h(App)
})
<script>
import Vue from 'vue'
import { mapGetters } from 'vuex'
export default {
name: "app",
mounted() {
let username = 'player1';
this.$store.dispatch("LOGIN", username);
}
}
</script>
store/auth.js 模块
const state = {
username: {},
isautheticated: {}
}
const getters = {
username: state => state.username,
isautheticated: state => state.isautheticated,
}
const mutations = {
SET_USERNAME: function(state, username){
state.username = username;
},
SET_ISAUTHENTICATED: function(state, isautheticated){
state.isautheticated = isautheticated;
},
}
const actions = {
LOGIN: ({commit, dispatch}, username) => {
if (!window.$cookies.get('username')) {
//not logged in, create cookie based on username
//save username in store by committing a mutation
commit(SET_USERNAME, username);
}
},
LOGOUT: ({commit, dispatch}) => {
//remove cookie
//window.$cookies.remove('username')
//clear username
commit(SET_USERNAME, '');
},
IS_AUTHENTICATED: ({commit, dispatch}) =>
{
//loop into your authentication module and clear the cookie if user becomes unauthenticated
//added an arbitrary isautheticated value to the store for an example
if(!state.isautheticated) {
commit(SET_USERNAME, '');
}
}
}
export default {
getters,
mutations,
actions,
state
}
如果您不调用服务来进行身份验证或获取用户数据,那么在存储 LOGIN 操作中使用此逻辑可能有点矫枉过正。