如何在 Vue 生态系统之外使用 Vue 3 响应式对象
我试图在微前端应用程序中传递这样创建的全局状态。但问题是我必须以某种方式“观察”更改,以便在 React 应用程序中设置 State。
globalState.js
import { reactive } from 'vue'
const globalState = reactive({
counter: 0
})
export default globalState
在 Vue 微前端中,我这样做并且工作正常
import { createApp } from 'vue'
import App from './App.vue'
export default (rootEl, globalState) => {
const app = createApp(App)
app.config.globalProperties.globalState = globalState
app.mount(rootEl)
}
但是在 React 应用程序中我正确地传递了引用,但是当计数器值发生变化时,我必须以某种方式检测它并调用 setState 以便重新渲染更改。问题是我如何观察 Vue 生态系统之外的反应式对象引用的变化。
I'm trying to pass global state created like this in micro front end applications. But the problem is that I have to "watch" for changes somehow in order to setState for example in a React app.
globalState.js
import { reactive } from 'vue'
const globalState = reactive({
counter: 0
})
export default globalState
In Vue micro front ends im doing this and it is working fine
import { createApp } from 'vue'
import App from './App.vue'
export default (rootEl, globalState) => {
const app = createApp(App)
app.config.globalProperties.globalState = globalState
app.mount(rootEl)
}
However in a React app I pass the reference correctly but when counter value changes I have to somehow detect it and call setState in order to rerender the change. The Question is how can I watch for changes of this reactive object reference outside Vue ecosystem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Reactivity API 可作为独立库使用(与
vue package) 可以在 Vue 上下文之外使用。
@vue/reactivity
包含reactive()
/ref()
。并且@vue-reactivity/watch
包括watch()
/watchEffect()
。例如,您可以使用
watchEffect
(或watch
)来记录globalState.counter
的新值并将其显示在页面:演示 1
在 React 应用程序中,您可以使用
watch
记录globalState.counter
的新值,然后调用组件的setState()
来重新渲染组件:演示 2
The Reactivity API is available as standalone libraries (separate from the
vue
package) that can be used outside the context of Vue.@vue/reactivity
includesreactive()
/ref()
. And@vue-reactivity/watch
includeswatch()
/watchEffect()
.For example, you could use a
watchEffect
(orwatch
) to log the new value ofglobalState.counter
and display it in an element on the page:demo 1
In a React app, you could use a
watch
to log the new value ofglobalState.counter
and then call a component'ssetState()
to re-render the component:demo 2
最新版本的
@vue/reactivity
不导出watch
和watchEffect
API,因此此处标记的答案不再起作用。相反,您将使用
effect
函数,其作用与
watchEffect
类似,但不返回取消订阅函数。您将使用提供的stop
函数并传递effect
的返回值。The latest versions of
@vue/reactivity
do not export thewatch
andwatchEffect
APIs, so the marked answer here does not work anymore.Instead, you will use the
effect
function, which acts similarly towatchEffect
but does not return an unsubscribe function. You'll use the providedstop
function and pass the returned value ofeffect
.