首页 > 解决方案 > 如何在 Nuxt JS 中异步全局 Mixin 数据?

问题描述

首先,让我分享我的工作流程。在我的 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 数据?

标签: javascriptvue.jsnuxt.jsvue-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
}
}


推荐阅读