【问题标题】:How to load data into Vue from an external file using Axios如何使用 Axios 将数据从外部文件加载到 Vue
【发布时间】:2018-09-22 23:54:35
【问题描述】:

您将如何用外部 JSON 文件替换本示例中的“图像”数据数组?基本上我想用 axios 从外部获取/获取这些数据,但是在这个例子中有些东西还没有完全工作。非常感谢任何线索!

如果您更喜欢以这种方式查看,我还为此示例创建了一个 CodePen,无需外部参考即可工作。非常感谢! https://codepen.io/FloydGekko/pen/eLoRBQ

这是 html、css 和 vue.js 代码:

<head>
    <style>
        [v-cloak] {
          display: none;
        }

        .imageBlock{
            width:100%;
            margin:10px;
        }
        div.polaroid {
            width:310px;
            height:440px;
            margin:10px;
            background-color: white;
            box-shadow: 6px 4px 8px 0 rgba(0, 0, 0, 0.2), 6px 6px 20px 0 rgba(0, 0, 0, 0.19);
            margin-bottom: 25px;
            border-radius: 18px
        }
        div.container {
            text-align: center;
            padding: 10px 20px;
        }
    </style>
</head>

<body>

<div id="vue" v-cloak>
    <h2 align="center">
        Show
    <select v-model="currentKind" @change="onChange">
        <option v-for="kind, index in kinds" :value="kind" :key="`kind_${index}`">{{kind ? kind : 'kind...'}}</option>
    </select>
    <select v-model="currentColor" @change="onChange">
        <option v-for="color, index in colors" :value="color" :key="`kind_${index}`">{{color ? color : 'color...'}}</option>
    </select>
        and
     <select v-model="currentShape" @change="onChange">
        <option v-for="shape, index in shapes" :value="shape" :key="`kind_${index}`">{{shape ? shape : 'shape...'}}</option>
    </select>
    </h2>

    <isotope
            id="root_isotope"
            ref="isotope"
            :options='options'
            :list="images"
            align="center">
        <div class="polaroid" align="center"
            v-for="(image, index) in images"
            class="imageBlock"
            :key="image.id">
            <a target="_blank"  :href="image.url"><img border="0" :src="image.pic" alt=""
            style="
                border-radius: 20px;
                display: block;
                margin-left: auto;
                margin-right: auto;
                width: 100%;">
            </a>
            <div class="container">
                <a target="_blank"  :href="image.url">
                <h3 align="center">{{image.title}}</h3>
                </a>


            <!--<h1>{{image.kind}}</h1>
            <h1>{{image.color}}</h1>
            <h1>{{image.shape}}</h1>
            <h1>{{image.id}}</h1>-->
            </div>
        </div>
    </isotope>
    <h2 align="center">
        <button @click="reset">Show all</button>
    </h2>
</div>


<script src='https://unpkg.com/vue/dist/vue.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js'></script>
<script src='https://npmcdn.com/isotope-layout@3.0.6/dist/isotope.pkgd.min.js'></script>
<script src='https://rawgit.com/David-Desmaisons/Vue.Isotope/master/src/vue_isotope.js'></script>
<script src='https://unpkg.com/axios/dist/axios.min.js'></script>

<script>
    let currentKind = null;
    let currentColor = null;
    let currentShape = null;
    let imageSearchString = null;


    var vm = new Vue({
        el: '#vue',
        data() {
            return {
                currentKind:'',
                currentColor:'',
                currentShape:'',
                options: {
                    itemSelector: ".imageBlock",
                    getSortData: {
                      id: "id"
                    },
                    sortBy : "id",
                    getFilterData: {
                        Finder: function(itemElem) {
                            let kindSearch = currentKind ? itemElem.kind.indexOf(currentKind) !== -1 : true;
                            let colorSearch = currentColor ? itemElem.color.indexOf(currentColor) !== -1 : true;
                            let shapeSearch = currentShape ? itemElem.shape.indexOf(currentShape) !== -1 : true;
                            return kindSearch && colorSearch && shapeSearch
                        },
                    },
                },
                images: '',
            };
        },
        computed: {
            kinds(){
                let allTags = _.flatten(this.images.map(image => image.kind))
                return [''].concat(_.uniq(allTags))
            },
            colors(){
                let allTags = _.flatten(this.images.map(image => image.color))
                return [''].concat(_.uniq(allTags))
            },
            shapes(){
                let allTags = _.flatten(this.images.map(image => image.shape))
                return [''].concat(_.uniq(allTags))
            },
        },
        mounted(){
            setTimeout(()=>{
                this.onChange()
            }, 200)
        },

        created: function () {
            this.loadImages();
        },
        methods: {
            onChange: function() {
                currentColor = this.currentColor;
                currentShape = this.currentShape;
                currentKind = this.currentKind;

                this.$refs.isotope.filter('Finder');
                this.$refs.cpt.layout('packery');
            },
            reset(){
                currentColor = '';
                currentShape = '';
                currentKind = '';

                this.currentColor = '';
                this.currentShape = '';
                this.currentKind = '';
                this.onChange()
            },

            // THIS IS THE PART OF THE CODE IN QUESTION I THINK
            loadImages: function () {
                var vm = this;
                axios.get('myimagedata.json')
                .then(function (response) {
                    vm.images = response.data.images;
                })
                .catch(function (error) {
                    vm.images = 'An Error occured.' + error;
                });
            }
        },
    });

</script>


</body>

</html>

这是我尝试用 axios 加载的外部 JSON 文件“myimagedata.json”:

{
    "images": [
        {
            "id": 1,
            "kind": ["A"],
            "color": ["Green", "Blue"],
            "shape": ["Square"],
            "pic": "http://r.ddmcdn.com/s_f/o_1/cx_462/cy_245/cw_1349/ch_1349/w_720/APL/uploads/2015/06/caturday-shutterstock_149320799.jpg",
            "url": "http://r.ddmcdn.com/s_f/o_1/cx_462/cy_245/cw_1349/ch_1349/w_720/APL/uploads/2015/06/caturday-shutterstock_149320799.jpg",
            "title": "A"
        },
        {
            "id": 2,
            "kind": ["B"],
            "color": ["Green", "Red"],
            "shape": ["Circle"],
            "pic": "https://www.kimballstock.com/pix/DOG/05/DOG-05-JE0078-01P.JPG",
            "url": "https://www.kimballstock.com/pix/DOG/05/DOG-05-JE0078-01P.JPG",
            "title": "B"
        }
    ]
}

【问题讨论】:

  • 我可以看看你在axios 上尝试过的loadImages() 方法吗?

标签: vue.js axios


【解决方案1】:

axios 中,您应该能够执行以下操作。您可能需要写一个var self = this。外部库将this 重写为自己的,因此要访问vue this 变量,您需要预先设置一个变量并使用新变量来设置您的数据。以后请显示您的问题代码,例如您的loadImages() 以及您遇到的错误。

var self = this
axios.get('/myimagedata.json')
  .then(function (response) {
    self.images = response.data.images
  })
  .catch(function (err) {
    console.error(err)
  })

在此处回复您的json

{
"images": [{
        "id": 1,
        "kind": ["A"],
        "color": ["Green", "Blue"],
        "shape": ["Square"],
        "pic": "http://r.ddmcdn.com/s_f/o_1/cx_462/cy_245/cw_1349/ch_1349/w_720/APL/uploads/2015/06/caturday-shutterstock_149320799.jpg",
        "url": "http://r.ddmcdn.com/s_f/o_1/cx_462/cy_245/cw_1349/ch_1349/w_720/APL/uploads/2015/06/caturday-shutterstock_149320799.jpg",
        "title": "A"
    },
    {
        "id": 2,
        "kind": ["B"],
        "color": ["Green", "Red"],
        "shape": ["Circle"],
        "pic": "https://www.kimballstock.com/pix/DOG/05/DOG-05-JE0078-01P.JPG",
        "url": "https://www.kimballstock.com/pix/DOG/05/DOG-05-JE0078-01P.JPG",
        "title": "B"
    }
]

}

【讨论】:

  • 我添加了您的建议,但它仍然不会从 JSON 加载数据。我觉得它非常接近,但缺少一点点。我将最初的问题更新为最新版本,并实施了您的建议。非常感谢!
  • 没问题。我注意到您将图像设置为字符串而不是空数组。将images: '' 更改为images:[]。在加载图像之前,您的 computed 组件无法在空字符串上加载地图。
  • 特拉弗,你就是男人!它正在工作!非常感谢您的帮助并解决了这个问题。非常感谢!
  • 它基本上可以在 Firefox 中运行,但不幸的是不能在 Chrome 中运行。此外,当我在服务器上运行它时,我会收到“跨源请求被阻止”,所以我尝试仅在 vue.js 中执行此操作,并在此处创建了一个新帖子:stackoverflow.com/questions/52548952/…
猜你喜欢
  • 2019-03-04
  • 2018-02-10
  • 1970-01-01
  • 2020-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多