반응형
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
반응형
'IT이야기' 카테고리의 다른 글
C에서 긴 인쇄문을 여러 줄로 나눌 수 있는가? (0) | 2022.05.08 |
---|---|
Java, "각각" 루프의 현재 인덱스/키를 가져오는 방법 (0) | 2022.05.08 |
주니트와 함께 하는 인텔리제이 아이디어 4.7 "!!!JUnit 버전 3.8 이상 예상:" (0) | 2022.05.08 |
문자열에서 문자 발생 횟수를 계산하는 방법 (0) | 2022.05.08 |
vuejs - 동적 입력 'synamic' (0) | 2022.05.08 |