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>
        <br />
        Evaluated: <component v-bind:is="Evaluated" v-bind:player="player"/>
    `,
    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")

Email me , or tweet @redblobgames, or comment: