在带有 JSON 的 Vue 组件中使用递归 [英] Using recursion in a Vue component with JSON

查看:20
本文介绍了在带有 JSON 的 Vue 组件中使用递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一组循环使用 JSON 的嵌套模板.它输出键,检查值是否不是对象,如果不是对象则输出值,否则它会更深入并遍历该属性的内部对象/数组.目前它大约有 3 层深,但可能需要更进一步.

这使它成为递归的一个很好的候选者.我是前端语言/框架的新手,在寻找如何使用 Vue 动态遍历 JSON 的好资源时,我很难找到好的资源.这是我能做到的最好的,但我不使用可预测的属性,如标签/节点/节点.

我想一个很好的起点是 Vue.component 模板.如何从主Vue实例传入JSON,然后如何设置模板动态遍历JSON?

HMTL

<html lang="zh-cn"><头><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:递归</title><!-- CDNs --><脚本src="https://code.jquery.com/jquery-3.3.1.min.js"完整性="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="crossorigin="匿名"></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><身体><main id="应用程序"><模板><部分><递归组件></递归组件></节></模板></main></html>

Javascript

$(function () {//获取 JSON$.getJSON("./data.json", 函数 (json) {app.json = json});Vue.component('递归组件', function() {模板:`<递归组件v-if="节点 !== 空"v-for="(node, key) 在节点中":nodes="node.nodes":key="节点.key"></递归组件>`});var app = new Vue({el:`#app`,数据: {json: 空}});});

通用 JSON

<代码>{细节": {"制造商": "宝马",座位":4,引擎": {扭矩":500,马力":600},中断":{正面": {"类型": "XYZ",容量":1234}}}}

解决方案

解决方案的关键只是检查数据是值还是对象,我做了这个例子,假设值只是数字和字符串(因为要检查如果变量是一个对象非常复杂 StackOverflow),那么递归组件只会相应地显示键/值.

const jsonData = {细节": {"制造商": "宝马",座位":4,引擎": {扭矩":500,马力":600},中断":{正面": {"类型": "XYZ",容量":1234}}}};Vue.component("my-recursive-component", {模板:'#my-recursive-component',道具:[深度",有效载荷"],数据() {},计算:{缩进(){返回 { 变换:`translate(${this.depth * 10}px)` }},类型() {if (typeof this.payload === "string" || typeof this.payload === "number") {返回值";}返回对象";},列表() {if (this.type === "obj") {返回 Object.keys(this.payload);}返回未定义;}}});const app = new Vue({el: "#app",数据() {json数据},});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script><div id="应用程序">递归组件演示:<我的递归组件:payload="jsonData":深度=0"></my-recursive-component>

<script type="text/x-template" id="my-recursive-component"><div>

<div v-for="列表中的项目">键:{{item}}<我的递归组件:payload="payload[item]":depth="深度 + 1"><我的递归组件/>

值:{{有效载荷}}

</script>

I currently have a set of nested templates that loops through JSON. It outputs the key, checks if the value is not an object, outputs the value if it's not an object, otherwise it goes deeper and traverses the inner object/array for that property. It goes about 3 layers deep currently, but may potentially have to go further.

This makes it a good candidate for recursion. I'm new to front-end languages/frameworks, and I am having trouble finding good resources on finding a good resource for how to traverse JSON dynamically with Vue. This was the best I could, but I'm not using predictable properties like label/node/nodes.

I guess a good place to start would be the Vue.component template. How do I pass in the JSON from the main Vue instance, and then how do I set the template to dynamically traverse the 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
    }
  });
});

Generic JSON

{
  "details": {
    "manufacturer": "BMW",
    "seats": 4,
    "engine": {
      "torque": 500,
      "hp": 600
    },
    "breaks": {
      "front": {
        "type": "XYZ",
        "capacity": 1234
      }
    }
  }
}

解决方案

The key of the solution is just checking if the data is a value or an object, I made this example assuming values are only numbers and strings (because to check if variable is an object is quite complicated StackOverflow), then the recursive component just displays the key/value accordingly.

const jsonData = {
  "details": {
    "manufacturer": "BMW",
    "seats": 4,
    "engine": {
      "torque": 500,
      "hp": 600
    },
    "breaks": {
      "front": {
        "type": "XYZ",
        "capacity": 1234
      }
    }
  }
};

Vue.component("my-recursive-component", {
  template: '#my-recursive-component',
  props: ["depth", "payload"],
  data() {
  },
  computed: {
    indent() {
      return { transform: `translate(${this.depth * 10}px)` }
    },
    type() {
      if (typeof this.payload === "string" || typeof this.payload === "number") {
        return "value";
      }
      return "obj";
    },
    list() {
      if (this.type === "obj") {
        return Object.keys(this.payload);
      }
      return undefined;
    }
  }
});

const app = new Vue({
  el: "#app",
  data() {
    jsonData
  },
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>

<div id="app">
  Recursive Component Demo:
  <my-recursive-component
    :payload="jsonData"
    :depth="0"
  >
  </my-recursive-component>
</div>

<script type="text/x-template" id="my-recursive-component">
  <div>
    <div 
      v-if="type === 'obj'" :style="indent">
      <div v-for="item in list">
        Key: {{item}}
        <my-recursive-component
          :payload="payload[item]"
          :depth="depth + 1"
          >
         <my-recursive-component/>
       </div>
    </div>
    <div 
      v-if="type === 'value'" :style="indent">
      Value: {{payload}}
    </div>
  </div>
</script>

这篇关于在带有 JSON 的 Vue 组件中使用递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆