【问题标题】:How to async global Mixin data in Nuxt JS?如何在 Nuxt JS 中异步全局 Mixin 数据?
【发布时间】:2021-08-23 02:33:45
【问题描述】:

首先,让我分享一下我的工作流程。在我的 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
        })
      },
}

在那之后,我创建了一个插件来保存我的 mixin。在 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 数据?

【问题讨论】:

    标签: javascript vue.js nuxt.js vue-mixin


    【解决方案1】:

    我认为,如果您使用计算属性而不是数据值,您的问题将得到解决。 此外,您可以安装@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
    }
    }

    【讨论】:

      猜你喜欢
      • 2020-08-04
      • 2021-04-16
      • 2020-08-27
      • 1970-01-01
      • 2021-08-27
      • 2018-11-16
      • 2019-12-06
      • 1970-01-01
      • 2019-08-16
      相关资源
      最近更新 更多