将HTML或组件传递给Vue Plugin



我已经创建了基本的Vue组件,如下所示:

<template>
<div class="example">
/* here render the component or HTML passed by pluing */
</div>
</template>
<script lang="ts">
import Vue from 'vue';
export default Vue.extend({
name: 'Example',
});
</script>

现在我需要创建一个插件,将呈现任何HTML或组件传递给Example.我知道插件的基本语法和如何在Vue中使用它们,但不知道如何做这个任务,因为我是一个新手到Vue

export default {
install(vue, opts){ 
/* how to take the component or HTML and pass to `Example` Component */
}
}

我需要在ve2中实现这些

您可以使用slot在任何组件中渲染任意HTML。

你的示例组件:

<template>
<div class="example">
<slot />
</div>
</template>
<script lang="ts">
import Vue from 'vue';
export default Vue.extend({
name: 'Example',
});
</script>

然后像这样使用:

<template>
<example>
<div>Render me inside the slot</div>
</example>
</template>

它将产生如下呈现的HTML:

<div class="example">
<div>Render me inside the slot</div>
</div>

然后在你的插件中,你可以使用你的Example组件并传递任何你想要的html

更新:这就是你的插件看起来的样子。只需在其中创建一个全局组件

import Vue from 'vue'
const ExamplePlugin = {
install(Vue){
Vue.component('Example', {
name: 'Example',
template: '<div class="example"><slot /></div>'
})
}
}

然后你可以Vue.use(ExamplePlugin)Example组件将在您的应用程序中全局可用

最新更新