Skip to content

变量同步 - useSyncRef

Vueuse 的 syncRefsyncRefs 的封装版本,与原方法功能完全相同,目的在于简化代码。因此,在阅读本文档之前,需要先了解原始方法的使用方式和作用。

useSyncRefs

根据 source 的值创建一个 ref 变量 target,当 source 发生变化时,target 会自动同步更新。

基本用法

js
// 之前
const source = ref('hello')
const target = ref('target')

const stop = syncRefs(source, target)

// 现在
const source = ref('hello')
const target = useSyncRefs(source)

console.log(target.value) // hello

source.value = 'foo'
console.log(target.value) // foo

target.value = 'bar'
console.log(source.value) // foo,反之不会同步

如果你也写过类似的代码:

js
const props = definedProps({
  val: {
    type: String,
    required: true,
  },
})

const localValue = ref(props.val)

watchEffect(() => {
  localValue.value = props.val
})

const onChangeValue = newValue => {
  localValue.value = newValue
}

使用 useSyncRefs,你能够轻松地实现相同的功能。

js
import {useSyncRefs} from '@ifanrx/uni-mp'

const props = definedProps({
  val: {
    type: String,
    required: true,
  },
})

const localValue = useSyncRefs(() => props.val) 

// 不再需要
const localValue = ref(props.val) 

// watchEffect(() => {
//   localValue.value = props.val
// })

const onChangeValue = newValue => {
  localValue.value = newValue
}

useSyncRef

useSyncRef 基于 Vueuse 的 syncRef 进行封装,其主要作用就是创建一个双向同步的 ref 变量,也可以设置为只对某个方向进行(ltrrtl),支持在同步的时候进行自定义转换。

useSyncRef 无法满足使用时,应考虑直接使用 syncRef

基本用法

js
// 之前
const a = ref('a')
const b = ref('b')

const stop = syncRef(a, b)

// 现在
const a = ref('a')
const b = useSyncRef(a)

b.value = 'foo'
console.log(a.value) // foo

a.value = 'bar'
console.log(b.value) // bar

双向同步

useSyncRef 默认为双向同步,这意味着无论修改哪一边的值,都将自动同步到另一边:

js
const source = ref(1)
const target = useSyncRef(source)

source.value++
console.log(target.value) // 2

target.value++
console.log(source.value) // 3

WARNING

需要注意的是,开启双向同步时,仅有当变量可写时才起作用:

js
const source = computed(() => props.id)
const target = useSyncRef(source)

target.value++
console.log(source.value) // 1,没有同步,因为 source 并不可写

单向同步

此外,你还可以自定义同步的方向:

js
const source = ref(1)

const target = useSyncRef(source, {
  // 左到右 e.g. source -> target
  direction: 'ltr', // 候选值:both(双向)、ltr(左到右)、rtl(右到左)
})

source.value++
console.log(target.value) // 2,说明会同步

target.value++
console.log(source.value) // 2,说明不会同步

转换器

你也可以自定义同步时如何取值:

js
const source = ref(1)

const target = useSyncRef(source, {
  direction: 'ltr',
  transform: {
    ltr: v => v * 10,
  },
})

source.value++
console.log(target.value) // 20

常见问题

useSyncRefs 和 useSyncRef 的区别

useSyncRefs 是 target 始终跟随 source,而 useSyncRef 可支持同步方向、转换器等选项。

请根据场景合理使用。

相关文档