主题
useSubject
将 RxJS Subject 绑定到 ref 并实现双向传递值的变化。
🌐 Bind an RxJS Subject to a ref and propagate value changes both ways.
示例
Available in the @vueuse/rxjs add-on.用法
🌐 Usage
ts
import { useSubject } from '@vueuse/rxjs'
import { Subject } from 'rxjs'
const subject = new Subject()
// setup()
const subjectRef = useSubject(subject)
// Changes to subjectRef.value will be pushed to the subject
subjectRef.value = 'new value'
// Values emitted by the subject will update subjectRef
subject.next('from subject')使用 BehaviorSubject
🌐 With BehaviorSubject
使用 BehaviorSubject 时,返回的引用会以被观察对象的当前值初始化,并且类型不包括 undefined:
🌐 When using a BehaviorSubject, the returned ref is initialized with the subject's current value and the type does not include undefined:
ts
import { useSubject } from '@vueuse/rxjs'
import { BehaviorSubject } from 'rxjs'
const subject = new BehaviorSubject('initial')
// setup()
const subjectRef = useSubject(subject) // Ref<string>, not Ref<string | undefined>
console.log(subjectRef.value) // 'initial'错误处理
🌐 Error Handling
如果你想为可能出现错误的 Subject 添加自定义的错误处理,可以提供一个可选的 onError 配置。没有这个配置时,RxJS 会将提供的 observable 中的任何错误视为“未处理的错误”,并会在新的调用栈中抛出,并报告给 window.onerror(如果你恰好在 node 中,则报告给 process.on('error'))。
🌐 If you want to add custom error handling to a Subject that might error, you can supply an optional onError configuration. Without this, RxJS will treat any error in the supplied observable as an "unhandled error" and it will be thrown in a new call stack and reported to window.onerror (or process.on('error') if you happen to be in node).
ts
import { useSubject } from '@vueuse/rxjs'
import { Subject } from 'rxjs'
const subject = new Subject()
// setup()
const subjectRef = useSubject(subject, {
onError: (err) => {
console.log(err.message) // "oops"
},
},)