繁体   English   中英

Vue 3 globalProperties 反应性

[英]Vue 3 globalProperties reactivity

我尝试将 Vue 2 插件迁移到 Vue 3,并且在安装 function 时我有这样的构造:

install(Vue, options) {
  const reactiveObj = {
    // ...
  };

  Vue.prototype.$obj = Vue.observable(reactiveObj);
}

然后我可以在任何组件中使用this.$obj访问它,并且当reactiveObj更改时它是反应性的。 但是在 Vue 3 中,我尝试做这样的事情:

import {reactive} from 'vue';

install(app, options) {
  const reactiveObj = reactive({
    // ...
  });

 app.config.globalProperties.$obj = reactiveObj;
}

然后我可以用this.$obj访问它,它是 Proxy object,但是当reactiveObj改变时它不是反应性的。 我怎样才能让它反应?

当我在我的组件中更改$obj的值时,我发布了适用于我的代码。 也许它可以帮助您理解代码中的问题。 这是我定义插件的"myPlugin.js"文件:

我的插件.js:

 import {reactive} from 'vue'; export default { install(app, options) { const reactiveObj = reactive({ id: 1, name: "my-name" }); app.config.globalProperties.$obj = () => { return reactiveObj }; } }

这是我的main.js文件中的插件注册:

 import { createApp } from 'vue' import App from './App.vue' import myPlugin from "./plugins/myPlugin" const app = createApp(App) app.use(myPlugin); app.mount('#app')

这是我的组件的代码,通过单击按钮更改$obj的值,您可以看到它是reactive的:

组件.vue:

 <template> <div> <p>{{ $obj() }}</p> <button @click="myFunc">click to change</button> </div> </template> <script> import {getCurrentInstance, reactive} from "vue"; export default { setup() { const thisApp= getCurrentInstance() const reactiveObj1 = reactive({ id: 2, name: "new-name" }); const myFunc = function () { thisApp.appContext.config.globalProperties.$obj().name = reactiveObj1.name thisApp.appContext.config.globalProperties.$obj().id = reactiveObj1.id } return { reactiveObj1, myFunc } } } </script>

我在组件中使用了getCurrentInstance ,因为我使用的是组合 API样式。 如果您使用“选项 API”样式,则可能不需要它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM