Ref/Reactive 作为店铺

Ref/Reactive as store

使用 ref 或 reactive 作为你的商店是个好主意吗?

我说的是我将创建一些 JS 文件,从那里导出 ref 变量,这样我就可以在我的代码中的任何地方使用它

// counter.store.js
export const counter = ref(0)
// counter.vue

<script setup>
import {counter} from './counter.store.js'
</script>

<template> 

<span> {{ counter }} </span>
<button @click="counter++"> Add </button>

</template>

这有什么缺点吗?

使用 Vue 反应性原语创建简单的全局存储非常好,甚至在 Vue 文档中也有描述 - Simple State Management with Reactivity API

主要缺点是:

  1. Vue Dev Tools 不支持(因此例如在 Dev Tools 中查看组件,您无法分辨什么是组件内部状态以及什么来自全局存储)
  2. possible issuesSSR场景
  3. 欠佳的开发体验 - 热模块更换不起作用