vueuse笔记-state

718 阅读2分钟

一、vueuse中createGlobalState 和createInjectionState的使用场景有什么区别?

在VueUse 中,createGlobalState createInjectionState 是两个用于状态管理的函数,用于在Vue .js 中创建全局状态和注入状态。

1.createGlobalState : -适用场景:用于创建全局的共享状态。 -特点: -创建的状态是全局的,可以在应用的任何地方使用。 -状态在组件之间共享,一个组件对状态的修改会影响其他使用该状态的组件。 -可以使用VueCompositionAPI 中的provide inject 配合使用来传递和使用全局状态。
2.createInjectionState : -适用场景:用于创建局部的注入状态。 -特点: -创建的状态是局部的,只能在特定的组件树范围内使用。 -注入状态可以在父组件提供,并通过VueCompositionAPI 中的provide inject 传递给子组件。 -子组件可以通过注入状态来访问其值。

总结: -createGlobalState 用于创建全局状态,适用于需要在整个应用中共享状态的场景。 -createInjectionState 用于创建局部的注入状态,在局部组件树中共享状态的场景。

二、useDebouncedRefHistory

带有debdedfilter的useRefHistory的简写
作用:用来对ref的数据进行快照,使用其返回的historyredoundo可对ref值进行历史快照、撤销、重做等操作 例:

//该函数在1000ms后,当计数器的值开始变化时,对其进行快照。
import { ref } from 'vue'
import { useDebouncedRefHistory } from '@vueuse/core'

const counter = ref(0)
const { history, undo, redo } = useDebouncedRefHistory(counter, { deep: true, debounce: 1000 })

三、useStorage

响应性的LocalStorage/SessionStorage
可以用来将数据存储在LocalStorage或SessionStorage中,存储的数据具有响应性默认是存在LocalStorage中 用法如下:

import { useStorage } from '@vueuse/core'

const state = useStorage('my-store', { hello: 'hi', greeting: 'Hello' })

// bind string with SessionStorage
const id = useStorage('my-id', 'some-string-id', sessionStorage) // returns Ref<string>

// delete data from storage
state.value = null