简体   繁体   中英

Reverse JSON data in Vue.JS using reverse()

I need to reverse the order of a JSON feed that is being used within a Vue.JS project.

In other frameworks the reverse() function has done the job. I have tried adding to the Vue.JS script but no joy yet.

Any ideas on other syntax I could try?

<script type="text/javascript">
new Vue({
    el: '#vueapp',
    data: {
        json: null
    },
    created: function () {
        var _this = this;
        $.getJSON('https://www.example.com/myfeed.json', function (json) {
            _this.json.reverse() = json;
        });
    }
});
</script>

So the last item in the JSON (the house on the side of the mountain in the example below), will display first when the page loads the JSON data.

https://jsfiddle.net/5kt9jurc/3/

Some Googling seems to show reverse() no longer works with Vue2 and is deprecated.

I think what you want is something like this:

_this.json = json.reverse();

That is, assuming json is an already parsed json array. Otherwise, first parse the json string:

const array = JSON.parse(jsonString);
this.data = array.reverse();

The way you are doing you are trying to assign a value to the result of an expression, which doesn't make much sense (right side values can't be assigned to).

You can reverse an array. Take a look at my fiddle . I replaced getJSON with fetch to use promises. Also you don't need to do var _this = this; It looks a bit weird. Since in Vue.js properties are reactive you can just set a value.

Here is a code:

const app = new Vue({
  el: '#app',
  data: {   
    items: []
  },
  created: function() {
    fetch('https://api.jsonbin.io/b/5b02b2bbc83f6d4cc7349a7b')
      .then(resp => resp.json())
      .then(items => {        
        this.items = items.reverse()
      })
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM