Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJs - Prepend to array

I'm trying to prepend data to an array in VueJs:

number: [

],

this.number.push({
    number: 1
})

How do I prepend rather than append?

like image 773
Ricky Barnett Avatar asked Feb 19 '16 22:02

Ricky Barnett


2 Answers

Unshift:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift

this.number.unshift({number: 1});

You can also pass multiple arguments to add them all:

this.number.unshift({number: 1}, {number: 2});

The return value is the new length of the array:

var foo = [1];
var bar = foo.unshift(2, 3, 4);
//foo = [2, 3, 4, 1]; bar = 4;
like image 59
Jeff Avatar answered Oct 12 '22 02:10

Jeff


Vue wraps an observed only this Array methods: push, pop, shift, unshift, splice, sort, reverse. You can use unshift or splice. For example:

 youArray.splice(0, 0, 'first item in Array');
like image 1
slava_slava Avatar answered Oct 12 '22 03:10

slava_slava