FlySky
FlySky

Reputation: 95

How to use Vue.compile in Vue 3?

How can I use Vue.$compile to compile function in Vue 3 runtime? I use the function in Vue 2. For example:

Vue.compile('<custom-component />');

Upvotes: 8

Views: 7779

Answers (3)

Betty St
Betty St

Reputation: 2860

You can use the render and h (creates VNode) functions:

import { render, h } from 'vue'
import Foo from "../components/Foo.vue"

function makeAFoo(props) {
  const vueComponent = h(Foo, props);
  const el = document.createElement('div')
  render(vueComponent, el)

  document.body.appendChild(el) // append it where you want 
}

Similar question: Vue 3 Append Component to the DOM: Best Practice

Upvotes: 0

Javaddict
Javaddict

Reputation: 566

Here is the component code I use for that

<template>
  <component v-if="component" :is="component" :="$attrs"/>
  <slot v-else></slot>
</template>

<script setup lang="ts">
import {compile, type Component, computed} from 'vue'

export interface Props {
  template?: string
}
const props = defineProps<Props>()

const component=computed(() => (props.template?{render : compile(props.template) }:undefined) as Component)

</script>

The slot is a fallback if there is no template. The component is reactive to template change

Upvotes: 0

Javaddict
Javaddict

Reputation: 566

import {compile} from "vue"

compile('<custom-component />')

that's all, almost the same!

Then you can do

render() {
  return h({render: compile('<custom-component />')})
}

As soon as you can't specify imports for the template, if it contains custom components they must have been registered previously with the app.component function at startup: vuejs.org/api/application.html#app-component

Upvotes: 5

Related Questions