【问题标题】:How can i access to 'download_url' in json using vuejs如何使用 vuejs 访问 json 中的“download_url”
【发布时间】:2020-09-26 12:42:44
【问题描述】:

我想在 meta 中获取 'tags' 和 'download url',我无法访问 json 中的 'download_url' 我该怎么做,作为后端我使用 wagtail cms,使用 vue js 是否很好带鹡鸰 cms(无头 cms)

<template>
<div>
  <div>
    <b-card-group deck v-for="item in results" :key="item.id">
      <b-card
      >
        <b-card-text>
          <div v-for="block in item.body" :key="block.id">
            <div v-if="block.type == 'heading'">
              <h2>{{block.value}}</h2>
            </div>
             <div v-if="block.type == 'image'">
              <img :src="'http://127.0.0.1:8000/api/v2/images/' + block.value">
            </div>
             <div v-if="block.type == 'paragraph'">
              <h2 v-html="block.value">{{block.value}}</h2>
            </div>
          </div>
        </b-card-text>

        >
      </b-card>
    </b-card-group>
  </div>
</div>
</template>

<script>

import axios from 'axios'
export default {
  name: 'Home',
  data () {
    return {
      results: null
    }
  },
  mounted () {
    axios.get('http://127.0.0.1:8000/api/v2/pages/?type=news.NewsPage&fields=intro,body,image_thumbnail')
      .then((response) => (
        this.results = response.data.items
      ))
  }
}
</script>

这里是 json api。我访问到图像的 id 并且不知道下一步该做什么

{
    "id": 3,
    "meta": {
        "type": "wagtailimages.Image",
        "detail_url": "http://localhost/api/v2/images/3/",
        "tags": [
            "gadget",
            "phone",
            "samsung"
        ],
        "download_url": "/media/original_images/affordable_new_9-7-inch_ipad_group_fan2_1_1.png"
    },
    "title": "affordable_new_9-7-inch_ipad_group_fan2 1 (1).png",
    "width": 528,
    "height": 357
}

【问题讨论】:

    标签: json vue.js axios


    【解决方案1】:

    假设 response.data.items 是您在上面显示的 json,您可以从那里提取您想要的内容。现在,您的组件在 this.response 中有整个 response.data.items。因此,如果您想要所有这些,请保留它。 您可以通过添加两条新数据将“标签”和“下载网址”存储到您的组件中,即将它们添加到您的数据中:

      data () {
        return {
          results: null,
          tags: null,
          downloadUrl: null
        }
    

    ...然后像这样从请求的响应中将它们设置在响应块中。

      mounted () {
        axios.get('http://127.0.0.1:8000/api/v2/pages/?type=news.NewsPage&fields=intro,body,image_thumbnail')
          .then((response) => (
    
            this.results = response.data.items
            this.tags = response.data.items.meta.tags
            this.downloadUrl = response.data.items.download_url
    
          ))
      }
    

    当处理像这样的嵌套响应对象时,它可以帮助用数据创建一个局部变量并以这种方式添加它。此外,如果您不需要整个响应,则可以避免存储它,而只需将您想要的响应中的数据存储到您的组件中。如果你想从 this.response 中得到一些东西,你将不得不深入研究它。只提取你需要的东西会更干净,然后在你的代码中使用它,只有一个{{myStuffIPulledOut}} vs {{response.thingIWantBefore.actualThing.}}

    【讨论】:

      猜你喜欢
      • 2017-06-22
      • 1970-01-01
      • 2017-03-24
      • 2022-12-17
      • 1970-01-01
      • 2020-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多