在 Vue 3 中,除了 ref
和 reactive
,还有其他几种方式可以用来管理状态,这些方式提供了不同的特性和用例。以下是一些常见的状态管理方法:
-
computed
:
computed
用于创建响应式的计算属性。它接收一个函数,返回值会根据依赖的响应式数据自动更新。<script setup> import { ref, computed } from 'vue'; const count = ref(0); const doubledCount = computed(() => count.value * 2); </script> <template> <p>Doubled count: {{ doubledCount }}</p> </template>
-
watch
和watchEffect
:
watch
和watchEffect
用于观察和响应 Vue 实例上的数据变动。watch
允许你指定一个或多个数据源,并执行副作用。watchEffect
自动追踪其依赖并在依赖改变时重新运行。
<script setup> import { ref, watch, watchEffect } from 'vue'; const count = ref(0); watch(count, (newValue, oldValue) => { console.log(`count changed from ${oldValue} to ${newValue}`); }); watchEffect(() => { console.log(`The count is now ${count.value}`); }); </script>
-
provide
和inject
:
provide
和inject
允许你在组件树中传递数据,无需使用 props 链。<script setup> import { provide, inject, ref } from 'vue'; const theme = ref('dark'); provide('themeKey', theme); // 在子组件中 const injectedTheme = inject('themeKey'); </script>
-
Vuex:
对于大型应用,Vuex 是官方的状态管理模式和库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。// 在 store/index.js import { createStore } from 'vuex'; export default createStore({ state: { count: 0 }, mutations: { increment(state) { state.count++; } } }); // 在组件中 <script setup> import { useStore } from 'vuex'; const store = useStore(); function increment() { store.commit('increment'); } </script>
-
Pinia:
Pinia 是 Vue.js 的官方状态管理库,是 Vuex 的演进版。它更轻量,更易于使用,并且与 Composition API 紧密集成。// 在 stores/useCounterStore.js import { defineStore } from 'pinia'; export const useCounterStore = defineStore('counter', { state: () => ({ count: 0 }), actions: { increment() { this.count++; } } }); // 在组件中 <script setup> import { useCounterStore } from '@/stores/useCounterStore'; const counterStore = useCounterStore(); function increment() { counterStore.increment(); } </script>
-
toRef
和toRefs
:
当你需要将reactive
对象中的单个属性或多个属性转换为ref
时,可以使用toRef
和toRefs
。<script setup> import { reactive, toRefs } from 'vue'; const state = reactive({ count: 0, message: 'Hello' }); const { count, message } = toRefs(state); </script>
每种状态管理方法都有其适用场景,选择哪种方式取决于你的具体需求和偏好。例如,对于简单的状态管理,ref
和 reactive
可能就足够了。而对于大型应用,你可能需要考虑使用 Vuex 或 Pinia 这样的状态管理库。