P粉0042876652023-08-25 18:25:26
An easier way is to use v-if or v-for.
Instead of dealing with the component directly, it is better to deal with the state of the component and let Vue's responsive magic work
This is an example, dynamically add a component (Toast), just operate the state of the component
Toast.vue file: The v-for here is reactive, whenever a new error is added to the errors object, it will be rendered
<script setup lang="ts">
import { watch } from 'vue';
import { ref, onUpdated } from 'vue';
import { Toast } from 'bootstrap';
const props = defineProps({
errors: { type: Array, default: () => [] },
});
onUpdated(() => {
const hiddenToasts = props.errors.filter((obj) => {
return obj.show != true;
});
hiddenToasts.forEach(function (error) {
var errorToast = document.getElementById(error.id);
var toast = new Toast(errorToast);
toast.show();
error.show = true;
errorToast.addEventListener('hidden.bs.toast', function () {
const indexOfObject = props.errors.findIndex((item) => {
return item.id === error.id;
});
if (indexOfObject !== -1) {
props.errors.splice(indexOfObject, 1);
}
});
});
});
</script>
<script lang="ts">
const TOASTS_MAX = 5;
export function push(array: Array, data): Array {
if (array.length == TOASTS_MAX) {
array.shift();
array.push(data);
} else {
array.push(data);
}
}
</script>
<template>
<div
ref="container"
class="position-fixed bottom-0 end-0 p-3"
style="z-index: 11"
>
<div
v-for="item in errors"
v-bind:id="item.id"
class="toast fade opacity-75 bg-danger"
role="alert"
aria-live="assertive"
aria-atomic="true"
data-bs-delay="15000"
>
<div class="toast-header bg-danger">
<strong class="me-auto text-white">Error</strong>
<button
type="button"
class="btn-close"
data-bs-dismiss="toast"
aria-label="Close"
></button>
</div>
<div class="toast-body text-white error-body">{{ item.msg }}</div>
</div>
</div>
</template>
ErrorTrigger.vue: Whenever a click event occurs, we push an error to the errors object
<script setup lang="ts"> import { ref, reactive } from 'vue'; import toast from './Toast.vue'; import { push } from './Toast.vue'; const count = ref(0); const state = reactive({ errors: [] }); function pushError(id: int) { push(state.errors, { id: id, msg: 'Error message ' + id }); } </script> <template> <toast :errors="state.errors"></toast> <button type="button" @click="pushError('toast' + count++)"> Error trigger: {{ count }} </button> </template>
Full example: https://stackblitz.com/edit/vitejs-vite-mcjgkl
P粉5981402942023-08-25 00:33:13
createVNode(component, props)
and render(vnode, container)
Create: Use createVNode()
to create a component-defined VNode
with props (for example, from *.vue
imported SFC), which can be passed to render()
to render on the given container element.
Destruction: Calling render(null, container)
will destroy the VNode
attached to the container. This method should be called to clean up when the parent component is unmounted (via the unmounted
lifecycle hook).
// renderComponent.js import { createVNode, render } from 'vue' export default function renderComponent({ el, component, props, appContext }) { let vnode = createVNode(component, props) vnode.appContext = { ...appContext } render(vnode, el) return () => { // destroy vnode render(null, el) vnode = undefined } }
Note: This method relies on internal methods (createVNode
and render
), which may be refactored or removed in future versions.
createApp(component, props)
and app.mount(container)
Create: Use createApp()
to create an application instance. This instance has a mount()
method that can be used to render the component on a given container element.
Destruction: Application instances have unmount()
methods to destroy application and component instances. This method should be called to clean up when the parent component is unmounted (via the unmounted
lifecycle hook).
// renderComponent.js import { createApp } from 'vue' export default function renderComponent({ el, component, props, appContext }) { let app = createApp(component, props) Object.assign(app._context, appContext) // 必须使用Object.assign在_context上 app.mount(el) return () => { // 销毁app/component app?.unmount() app = undefined } }
Note: This method creates an application instance for each component. If multiple components need to be instantiated in the document at the same time, it may cause considerable overhead.
<script setup> import { ref, onUnmounted, getCurrentInstance } from 'vue' import renderComponent from './renderComponent' const { appContext } = getCurrentInstance() const container = ref() let counter = 1 let destroyComp = null onUnmounted(() => destroyComp?.()) const insert = async () => { destroyComp?.() destroyComp = renderComponent({ el: container.value, component: (await import('@/components/HelloWorld.vue')).default props: { key: counter, msg: 'Message ' + counter++, }, appContext, }) } </script> <template> <button @click="insert">插入组件</button> <div ref="container"></div> </template>