Vue Dynamic Template

 from Red Blob Games
6 Jan 2023

Can we dynamically set the template of a Vue component? Why yes! Thanks to jacek on the Vue discord. There's a player object with health and gold as properties. This doesn't catch errors and you may have to reload to make the app work again.

import {reactive, ref, computed, createApp} from '/mjs/vue.v3.browser.js'

const App = {
    template: `
        Input: <input v-model="inputBox" size="60">
        <br />
        <button v-on:click="update">Copy input to template:</button>
        <br/>
        <code>{{expr}}</code>
        <div class="boxed">
          Evaluated: <component v-bind:is="Evaluated" v-bind:player="player"/>
        </div>
    `,
    setup() {
        const player = reactive({health: 10, gold: 5})
        const inputBox = ref("Health is {{ player.health }}, gold is {{ player.gold * 10 }}")
        const expr = ref(inputBox.value)
        const Evaluated = computed(() => ({
            props: ['player'],
            template: expr.value
        }))
        function update() {
            expr.value = inputBox.value
        }

        return {
            player,
            inputBox,
            expr,
            update,
            Evaluated,
        }
    },
}

let app = createApp(App)
app.mount("#app")

Hiws points out that if you want that template to have access to Vue components, those components need to be registered either at the app level or at the component level.

Related: we can create entirely new components at run time.

Email me , or comment here: