I’m trying to programmatically append a component to a container called toaster
. I’m using vuejs3
to accomplish this.
I create the #toaster
element and, with the information gathered from this article, add an addToast()
function so I can use it in other modules.
// @/App.vue
<template>
<div class="h-screen">
<Navbar />
<div id="toaster" class="absolute bottom-4 left-2 z-50"></div>
<router-view> </router-view>
</div>
</template>
<script>
import Navbar from "./components/Navbar.vue";
import Toast from "./components/Toasts.vue";
import Vue from "vue";
export default {
name: "RootApp",
components: {
Navbar,
},
setup() {
return {};
},
};
export function addToast(message, type) {
const toastClass = new Vue.extend(Toast);
const toastInstance = new toastClass({
propsData: {
message,
type,
},
});
toastInstance.$mount();
document.querySelector("#toaster")?.appendChild(toastInstance.$el);
}
</script>
I define the component here:
// @/components/Toast.vue
<template> ... </template>
<script>
import { ref, defineComponent } from "vue";
export default defineComponent({
name: "ToastComponent",
props: {},
setup(props) {
const toasts = ref([]);
const shown = ref(true);
setTimeout(() => {
shown.value = false;
return;
}, 3000);
return {
props,
shown,
toasts,
};
},
});
</script>
And finally, try to display a Toast in one of my views:
// @/views/LandingView.vue
<script>
import { ref } from "vue";
import { addToast } from "@/App.vue";
export default {
name: "LandingView",
components: {},
setup() {
const form = ref({
email: "",
password: "",
});
const handleFormSubmit = () => {
addToast("Hello World!", "success");
};
return { handleFormSubmit, form };
},
};
</script>
When handleFormSubmit()
fires, I get the following error:
Uncaught TypeError: can't access property "extend", vue__WEBPACK_IMPORTED_MODULE_2__.default is undefined
.
I’d appreciate any insight. Let me know if more info is needed.