【发布时间】:2018-08-13 18:20:51
【问题描述】:
我目前有一组通过 JSON 循环的嵌套模板。它输出键,检查值是否不是对象,如果不是对象则输出值,否则它会更深入并遍历该属性的内部对象/数组。它目前大约有 3 层深,但可能需要更深。
这使它成为递归的理想选择。我是前端语言/框架的新手,我很难找到好的资源来寻找如何使用 Vue 动态遍历 JSON 的好资源。 This was the best I could, but I'm not using predictable properties like label/node/nodes.
我想 Vue.component 模板是一个很好的起点。如何从主Vue实例传入JSON,然后如何设置模板动态遍历JSON?
HMTL
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Vue: Recursion</title>
<!-- CDNs -->
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.js"></script>
<!-- JS -->
<script src="app.js" charset="utf-8"></script>
</head>
<body>
<main id="app">
<template>
<section>
<recursive-component></recursive-component>
</section>
</template>
</main>
</body>
</html>
Javascript
$(function () {
// Get JSON
$.getJSON("./data.json", function (json) {
app.json = json
});
Vue.component('recursive-component', function() {
template: `
<recursive-component
v-if="node !== null"
v-for="(node, key) in nodes"
:nodes="node.nodes"
:key="node.key"
>
</recursive-component>`
});
var app = new Vue({
el: `#app`,
data: {
json: null
}
});
});
通用 JSON
{
"details": {
"manufacturer": "BMW",
"seats": 4,
"engine": {
"torque": 500,
"hp": 600
},
"breaks": {
"front": {
"type": "XYZ",
"capacity": 1234
}
}
}
}
【问题讨论】:
-
您是说您有一些 json 数据,并且您想将这些数据“导入”到您的 Vue 实例中以便我们使用它吗?
-
我已经在 Vue 实例中拥有数据,其中 getJSON 函数设置了实例变量。我想知道如何构建一个递归模板来输出数据。
标签: javascript json vue.js vuejs2 vue-component