【问题标题】:Parse XML from an API in Nuxt using XML2JS使用 XML2JS 从 Nuxt 中的 API 解析 XML
【发布时间】:2020-09-16 19:02:57
【问题描述】:

我正在尝试使用 XML2JS 循环遍历 nuxt 中的 API,然后循环遍历数据以将其显示在 html 文件中。

它在控制台登录时工作,但它没有在 HTML 中循环。它没有任何错误,只是空白,没有在 html 中显示任何内容。

    <template>
  <article>

<TheHeader />

    <h1>Destinations</h1>

  <main class="mt-8 mx-auto max-w-screen-xl px-4 sm:mt-12 sm:px-6 md:mt-20 xl:mt-24">


<section v-for="(mountain, index) in mountains" :key="index">

<div v-for="category in mountain.property" :key="category.id">


      <div class="lg:grid lg:grid-cols-12 lg:gap-8 mt-12">
        <div class="sm:text-center md:max-w-2xl md:mx-auto lg:col-span-6 lg:text-left">
          <h2 class="mt-1 text-4xl tracking-tight leading-10 font-extrabold text-gray-900 sm:leading-none sm:text-6xl lg:text-5xl xl:text-6xl">
            {{ category.propertyname }}
          </h2>
          <p class="mt-3 text-base text-gray-500 sm:mt-5 sm:text-xl lg:text-lg xl:text-xl">
            {{ category.propertyaddress }}
          </p>
        </div>
        <div class="mt-12 relative sm:max-w-lg sm:mx-auto lg:mt-0 lg:max-w-none lg:mx-0 lg:col-span-6 lg:flex lg:items-center">
          <div class="relative mx-auto w-full rounded-lg shadow-lg">
            <button type="button" class="relative block w-full rounded-lg overflow-hidden focus:outline-none focus:shadow-outline">
              <img class="w-full" :src="category.photos.img.main._url" :alt="category.photos.img.caption">
              <div class="absolute inset-0 w-full h-full flex items-center justify-center">
              </div>
            </button>
          </div>
        </div>
      </div>

</div>
</section>

    </main>

  </article>
</template>

<script>


const xml2js = require('xml2js');

  export default {
    data() {
      return {
        mountains: []
      }
    },

    async fetch() {
      this.mountains = await fetch('http://localhost:3000/api/')
      .then( res => res.text() )
      .then( data=> {

          const xml = data;

          xml2js.parseString(xml, (err, result) => {
              if(err) {
                  throw err;
              }

              const output = JSON.stringify(result, null, 4);

              console.log(output);
          });

      })
    }

  }
</script>

JSON:

{
"scdata": {
    "property": [
        {
            "propertycode": "123456"

任何帮助将不胜感激,如果您需要我提供更多信息,请告诉我。

谢谢。

【问题讨论】:

    标签: vue.js nuxt.js xml2js


    【解决方案1】:

    我猜你没有向山区返回任何数据。可能这就是为什么您在 const 输出

    中获得数据时没有在视觉上获得任何显示的原因

    所以,请尝试用下面的替换 fetch 函数

    <template>
    <div class="container">
      <h1>Test demo of xml parse</h1>
      <div v-for="(category, index) in mountains" :key="index">
        <div class="property-name"> <h3>Property Code:</h3><span>category.propertycode</span>
        </div>
      </div>
    </div>
    </template>
    
    <script>
    const xml2js = require('xml2js');
    export default {
      data() {
        return {
          mountains: []
        }
      },
      methods: {
        xmlToJSON: (str, options) => {
          return new Promise((resolve, reject) => {
            xml2js.parseString(str, options, (err, jsonObj) => {
              if (err) {
                return reject(err);
              }
              resolve(jsonObj);
            });
          });
        }
      },
      async fetch() {
        const xmlData = await fetch('<YOUR-API-URL>')
          .then(res => res.text())
          .then(data => {
            console.log('<<==');
            const xml = data;
            return data;
          });
        const jsonData = await this.xmlToJSON(xmlData);
        if (jsonData && jsonData.scdata && jsonData.scdata.property) this.mountains = jsonData.scdata.property
      }
    }
    </script>
    

    【讨论】:

    • 感谢您的评论,这似乎仍然没有输出模板中的值供我访问。这有什么问题吗?
      {{ category.property } } {{ category.propertyaddress }}
    • 我更新了代码,请检查一下,实际上你在 vueJs 文件中解析错误。请尝试使用上面的代码,它将显示 propertyCode。你可以根据你的要求写
    • 这太好了,如果你能提供帮助,再问两个问题,当我使用 {{ category.propertyname }} {{ category.countryiso }} 时,它显示为 [ "London Eye" ] [ "GB " ] 有没有办法删除文本周围的 [""]?当我使用 :src="category.photos.img.main.url" 我得到 TypeError: Cannot read property 'main' of undefined, Image of the JSON -> imgur.com/a/AuRiysj
    • 我看到你在解析数组时犯了一个错误。请正确解析数组。如果您总是在数组中获得 propertyname 和 countryiso 而不是使用循环的任一迭代,并且如果您想显示第一个元素而不是简单地使用:category.propertyname[0] & category.countryiso[0] & 对于图像,您需要解析完整而不是直接使用 For image :src 可能是:category.photos[0]['img'][0]['main'][0]['url'][0]。更多联系我:cnviradiya.github.io
    猜你喜欢
    • 2019-03-15
    • 2014-08-30
    • 2012-06-09
    • 2018-10-31
    • 2019-10-24
    • 1970-01-01
    • 2017-09-04
    • 2015-04-25
    • 1970-01-01
    相关资源
    最近更新 更多