You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NuxtJS中如何通过Observable实时获取屏幕宽度值?

解决NuxtJS中实时判断屏幕宽度(移动端)的响应式问题

你的代码核心问题是直接将布尔值通过Vue.observable绑定到Vue原型上,原始类型(布尔、数字等)无法被Vue的响应式系统追踪,导致视图无法实时更新。以下是修正后的实现方案:

1. 修改插件代码(plugins/breakpoints.js)

将$isMobile改为包含响应式值的对象,同时添加防抖处理避免resize事件频繁触发:

import Vue from 'vue'

// 创建响应式对象,包装布尔值
Vue.prototype.$isMobile = Vue.observable({ value: window.innerWidth < 500 })

// 防抖函数,避免频繁触发resize
function debounce(func, delay) {
  let timeoutId
  return function() {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(func, delay)
  }
}

window.addEventListener(
  'resize',
  debounce(() => {
    Vue.prototype.$isMobile.value = window.innerWidth < 500
  }, 100) // 100ms防抖延迟,可按需调整
)

2. 组件中使用(pages/index.vue)

需要访问响应式对象的value属性才能触发视图更新:

<template>
  <section>
    <h1>isMobile {{ $isMobile.value }}</h1>
  </section>
</template>

<script>
export default {
  name: 'IndexPage'
}
</script>

关键说明

  • 响应式追踪:Vue.observable仅对对象的属性变化有效,原始类型无法被追踪,因此必须用对象包装布尔值。
  • 防抖处理:resize事件会在窗口拖动时连续触发,添加防抖能减少不必要的计算,提升性能。
  • SSR兼容:已在nuxt.config.js中设置ssr: false,确保插件仅在客户端运行,避免window is not defined错误。

内容的提问来源于stack exchange,提问作者Jim Parsons

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 15:15:56