如何在 Nuxt JS 中异步全局 Mixin 数据?

问题描述

首先,让我分享一下我的工作流程。在我的 nuxt 应用程序中,我试图通过获取用户的窗口宽度来跟踪用户是来自桌面还是移动设备。要做到这一点,

首先,我在我的 default.vue 中使用 js 的 window 对象来更新我商店中的高度和宽度变量。这是代码

//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
        })
      },}

在那之后,我创建了一个插件来保留我的 mixin。在 mixin 中,我通过从商店获取宽度变量值来填充我的 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 数据?

解决方法

我认为,如果您使用计算属性而不是数据值,您的问题将得到解决。 此外,您可以安装@nuxt-device 模块并使用它来检测每个页面中的当前设备。 如果这些方法不能解决您的问题,只需将值存储在状态中并通过 cookie 将它们持久化。

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({ 
    computed:{
       isMobile(){
          return store.getters.windowWidth<768;
       }
     }
   }) // Set up your mixin then
}
}