IT이야기

VueJS - 문자열 내에서 문자열 보간

cyworld 2022. 5. 8. 22:06
반응형

VueJS - 문자열 내에서 문자열 보간

VueJS에서 문자열 에서 템플릿 또는 스크립트에 문자열을 보간할 수 있는 방법이 있는가?예를 들어, 다음을 표시하려는 경우1 + 1 = 2대신에1 + 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사용자가 정의한다.나는 질문 속성을 계산된 속성으로 재구성할 수 있지만, 기존의 데이터 구조를 재치 있게 유지하고 싶다.

JsFiddle에 대한 작업 예를 제공하는 https://forum.vuejs.org/t/evaluate-string-as-vuejs-on-vuejs2-x/20392/2,에서 찾고 있던 솔루션을 찾았다. 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>

참조URL: https://stackoverflow.com/questions/52062680/vuejs-interpolate-a-string-within-a-string

반응형