VueJS - 一个字符串内插值字符串

问题描述 投票:1回答:1

在VueJS,是有办法的字符串内插一个字符串,无论是在模板或脚本?例如,我想下面,而不是显示1 + 1 = 21 + 1 = {{ 1 + 1 }}

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

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

编辑:为了更好地说明为什么需要这个,这里就是我的实际数据是这样的:

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将由用户定义。虽然我可以作为计算性能重建的问题性质,我宁愿保持机智现有的数据结构。

variables vuejs2 eval bind string-interpolation
1个回答
0
投票

我发现我一直在寻找从https://forum.vuejs.org/t/evaluate-string-as-vuejs-on-vuejs2-x/20392/2,它提供的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>
© www.soinside.com 2019 - 2024. All rights reserved.