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

Pinia中数组变为Proxy对象,Vue3模板中如何使用include()?

解决Pinia数组项中Proxy数组导致的includes调用错误

问题场景

在Pinia store中定义了包含数组属性的对象数组mainNavigation,示例数据如下:

mainNavigation: [
    {
    "_uid": "9acd58dd-a9de-4de1-bc2b-3e781cc42a59",
    "title": "Alla Produkter",
    "design": ["sale"],
    "divider": false,
    "component": "NestableNav",
    "permission": "all",
    "mobileButton": "Visa alla produkter",
    "desktopDesign": ["menuicon"],
  },
  // more objects
]

但在Vue3的setup函数或模板中调用item.desktopDesign.includes('menuicon')时触发500错误,typeof检测发现desktopDesign是下标为0的Proxy对象,尝试.value无效。

解决方案

  • 确保store数据初始化的正确性
    检查Pinia store中mainNavigation的初始化和修改逻辑,确认所有项的desktopDesign始终是数组类型——即使是空值也要初始化为[],避免被意外包装成单个Proxy值而非数组。

  • 用toRaw获取原始数组
    Vue3提供的toRaw方法可获取响应式包装的原始对象,直接调用原始数组的includes方法即可:

    // setup函数中使用
    import { toRaw } from 'vue'
    
    const hasMenuIcon = toRaw(item.desktopDesign).includes('menuicon')
    

    模板中需先将toRaw挂载到上下文,再使用:

    <template>
      <div v-if="toRaw(item.desktopDesign).includes('menuicon')">...</div>
    </template>
    
    <script setup>
    import { toRaw } from 'vue'
    // 将toRaw暴露给模板
    defineExpose({ toRaw })
    </script>
    
  • 手动解构Proxy为原始值
    若无法避免Proxy包装,可通过序列化再反序列化的方式转为原始数组,适合数据不频繁更新的场景:

    // setup函数中
    const hasMenuIcon = JSON.parse(JSON.stringify(item.desktopDesign)).includes('menuicon')
    

    模板中直接使用:

    <template>
      <div v-if="JSON.parse(JSON.stringify(item.desktopDesign)).includes('menuicon')">...</div>
    </template>
    
  • 规范Pinia state修改逻辑
    确保在store的actions中修改mainNavigation时,使用Pinia的正确方式(直接修改或$patch),避免非响应式修改导致数据异常包装:

    // store的actions示例
    updateNavigationItem(uid, updates) {
      const item = this.mainNavigation.find(i => i._uid === uid)
      if (item) {
        item.desktopDesign = updates.desktopDesign || []
      }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 19:45:32