简体   繁体   中英

How to expose a custom attribute added to the window object in Vue 3 using Vue Router

I have exposed a custom attribute added to the Window object to the client browser via the onMounted hook of a child component. Since the component was rendered inside the App.vue component it worked just fine, I was able to access the custom attribute (an object) from the browser, etc. But since the app needed more views I have implemented Vue Router and views so the way my app is rendering is different and now I'm trying to find a way to expose the object with the new folder structure:

Before Implementing vue router:

在此处输入图像描述

APP.vue Template:

<template>
  <WidgetContainer />
</template>

WidgetContainer Component onMounted Lifecycle Hook:

onMounted(async () => {
  window.myWidget = {
    load: retrieveEndUserJWT,
  };
});

And then I can do something in the WidgetContainer method:

const retrieveEndUserJWT = async (callback) => {
  //do something
};

Now after implementing the Vue router, I have changed my project structure a little bit so instead of just functional components I have views:

在此处输入图像描述

So now the App.vue template looks like this:

<template>
  <router-view></router-view>
</template>

The problem with this is that the exposed custom attribute added to the Window object (window.myWidget) never reaches the DOM because is on the OnMounted lifecycle hook of the WidgetContainer child component. Is there any way I can still have that object without compromising the logic of my widgetContainer child component? maybe emitting an event from there to the app.vue component?

Actually the answer was pretty simple. I just moved the implementation of the new attribute to the mounted hook of the App.vue and then call the child component method from this component.

<script setup>
import { onMounted } from "vue";
onMounted(() => {
  window.myWidget = {
    load: retrieveEndUserJWT,
  };
});
const retrieveEndUserJWT = async () => {
  console.log("Hello World");
};
</script>

<template>
  <router-view></router-view>
</template>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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