Intento migrar el complemento Vue 2 a Vue 3, y en la función de instalación tengo una construcción como esta:
install(Vue, options) { const reactiveObj = { // ... }; Vue.prototype.$obj = Vue.observable(reactiveObj); } Y luego puedo acceder a él con this.$obj en cualquier componente y es reactivo cuando cambia reactiveObj . Pero en Vue 3 trato de hacer algo como esto:
import {reactive} from 'vue'; install(app, options) { const reactiveObj = reactive({ // ... }); app.config.globalProperties.$obj = reactiveObj; } Y luego puedo acceder a él con this.$obj , es un objeto Proxy, pero no es reactivo cuando cambia reactiveObj . ¿Cómo puedo hacerlo reactivo?
Publico los códigos que me funcionan cuando cambio el valor de $obj en mi componente. Tal vez podría ayudarlo a comprender los problemas en su código. aquí está el archivo "myPlugin.js" donde definí el complemento:
miPlugin.js:
import {reactive} from 'vue'; export default { install(app, options) { const reactiveObj = reactive({ id: 1, name: "my-name" }); app.config.globalProperties.$obj = () => { return reactiveObj }; } } Y aquí está el registro del complemento en mi archivo 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') Y aquí está el código de mi componente donde al hacer clic en el botón se cambian los valores de $obj y se puede ver que es reactive :
componente.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 en mi componente, porque estoy usando el estilo API de composición . Tal vez no necesite eso si está usando el estilo "API de opciones".