반응형
Json을 Vue 구성 요소 및 루프에 전달
예상 출력값:
<div class="container">
<div class="wrapper">
<div class="title">Title 1</div>
<div class="text"><p>Text 1</p></div>
</div>
<div class="wrapper">
<div class="title">Title 2</div>
<div class="text"><p>Text 2</p></div>
</div>
...
</div>
이건 내 PHP 파일이야:
// Contains HTML markup
$array = [
['title' => 'Title 1', 'text' => '<p>Text 1<\/p>'],
['title' => 'Title 2', 'text' => '<p>Text 2<\/p>'],
...
];
<div class="container" data-content="'.json_encode($array).'">
<list-item v-for="item in list" v-bind:list-prop="item" v-bind:key ="item.title"></list-item>
</div>
그리고 이건 내 자바스크립트 파일이야.
var containers = document.querySelectorAll('.container');
if(containers.length > 0) {
for(var i=0; i<containers.length; i++)
buildList(containers[i]);
}
function buildList(el) {
Vue.component('list-item', {
props: ['listProp'],
template: '<div class="wrapper"><div class="title">{{ listProp.title }}</div><div class="text">{{ listProp.text }}</div></div>'
});
var container = new Vue({
el: el,
data: {
list: JSON.parse(el.dataContent)
}
});
}
에러가 난다.Unexpected token u in JSON at position 0 at JSON.parse
내가 분명히 뭔가 잘못하고 있는 것 같은데 어디인지는 잘 모르겠어.이것을 성취하기 위한 더 좋은 방법이 있는지 알고 싶다.다음과 같은 방법으로 답을 읽는다.:prop
하지만 내 경우에는 어떻게 실행해야 할지 모르겠어.
나는 이 제안이 정말 싫지만 PHP로 간단한 REST API를 만들지 않고도 할 수 있는 일이 있다.그런 다음 이 개체를 창 개체에 가지고 있으면 Vue.js 코드 내에서 해당 개체를 참조할 수 있다.
// Contains HTML markup
<?php
$array = [
['title' => 'Title 1', 'text' => '<p>Text 1<\/p>'],
['title' => 'Title 2', 'text' => '<p>Text 2<\/p>'],
...
];
?>
<script>
const titles = <?php echo $array; ?>
</script>
<div class="container">
<list-item v-for="item in list" v-bind:list-prop="item" v-bind:key ="item.title"></list-item>
</div>
참조URL: https://stackoverflow.com/questions/48757138/pass-json-to-vue-component-and-loop
반응형
'programing' 카테고리의 다른 글
프레임워크 셀 렌더러를 사용한 Ag 그리드가 스토어 변경 시 계속 재렌더링됨 (0) | 2022.03.13 |
---|---|
인쇄 함수 출력(비퍼 파이선 출력)을 플러시하려면 어떻게 해야 하는가? (0) | 2022.03.12 |
Redex를 사용하여 배열에서 요소 삭제 (0) | 2022.03.12 |
입력에 대한 렌더 기능 Vue에서 반응성 제거 (0) | 2022.03.12 |
오류를 유발하는 VueJS crollBehavior() 매개 변수 (0) | 2022.03.12 |