首先,让我分享我的工作流程。在我的 nuxt 应用程序中,我试图通过获取用户的窗口宽度来跟踪用户是来自桌面还是移动设备。要做到这一点,
首先,我在 default.vue 中使用 js 的 window 对象来更新商店中的 height 和 width 变量。这是代码
//default.vue
created() {
if (process.browser) {
window.addEventListener('resize', this.handleResize);
this.handleResize(window.innerHeight, window.innerWidth);
}
},
}
methods: {
handleResize() {
this.$store.commit('setwindowheightwidth', {
height: window.innerHeight,
width: window.innerWidth
})
},
}
之后,我创建了一个插件来保存我的 mixins。在 mixin 中,我通过从 store 中获取 width 变量值来填充我的 isMobile 变量。
import Vue from "vue"
export default ({store}) => {
// Make sure to pick a unique name for the flag
// so it won't conflict with any other mixin.
if (!Vue.__my_mixin__) {
Vue.__my_mixin__ = true
Vue.mixin({
data: function() {
return {
isMobile: store.getters.windowWidth<768,
}
},
}) // Set up your mixin then
}
}
现在,正如我所期望的那样,我在每个组件和页面中都获取了这些数据。但是当我第一次加载页面或刷新页面时,该值返回 true!即使实际值是假的。但是,如果我通过导航转到其他页面或返回到初始页面(不刷新),我将获得实际值。因此,由于某种原因,该值似乎在我的任何页面的初始加载时都没有更新。通常我通过使用 async-await 获取数据来解决这类问题,但不确定在哪里使用它。如何在页面加载时从其初始状态更新 mixin 数据?