VueJS - Interpolate a string within a string

混江龙づ霸主 提交于 2020-02-28 13:34:32

问题


In VueJS, is there a way to interpolate a string within a string, either in the template or in the script? For example, I want the following to display 1 + 1 = 2 instead of 1 + 1 = {{ 1 + 1 }}.

<template>
    {{ myVar }}
</template>

<script>
    export default {
        data() {
            "myVar": "1 + 1 = {{ 1 + 1 }}"
        }
    }
</script>

Edit: to better illustrate why I would need this, here's what my actual data looks like:

section: 0,
sections: [
    {
        inputs: {
            user: {
                first_name: {
                    label: "First Name",
                    type: "text",
                    val: ""
                },
                ...
            },
            ...
        },
        questions:  [
            ...
            "Nice to meet you, {{ this.section.inputs.user.first_name.val }}. Are you ...",
            ...
        ]
    },
    ...
],

this.section.inputs.user.first_name.val will be defined by the user. While I could rebuild the question properties as computed properties, I would rather keep the existing data structure in tact.


回答1:


I found the solution I was looking for from https://forum.vuejs.org/t/evaluate-string-as-vuejs-on-vuejs2-x/20392/2, which provides a working example on JsFiddle: https://jsfiddle.net/cpfarher/97tLLq07/3/

<template>
    <div id="vue">
        <div>
            {{parse(string)}}
        </div>
    </div>
</template>

<script>
    new Vue({
        el:'#vue',
        data:{
            greeting:'Hello',
            name:'Vue',
            string:'{{greeting+1}} {{name}}! {{1 + 1}}'
        },
        methods:{
            evalInContext(string){
                try{
                    return eval('this.'+string)
                } catch(error) {
                    try {
                        return eval(string)
                    } catch(errorWithoutThis) {
                        console.warn('Error en script: ' + string, errorWithoutThis)
                        return null
                    }
                }
            },
            parse(string){
                return string.replace(/{{.*?}}/g, match => {
                    var expression = match.slice(2, -2)
                    return this.evalInContext(expression)
                })
            }
        }
    })
</script>


来源:https://stackoverflow.com/questions/52062680/vuejs-interpolate-a-string-within-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!