Vue Js Push Array to Array:In Vue.js, you can push an array into another array using the push
method. First, you need to access the target array using its reference, and then you can use the push
method to add the desired array as a new element. For example, if you have an array called targetArray
and another array called sourceArray
, you can push the elements of sourceArray
into targetArray
with the following code: targetArray.push(...sourceArray)
. The spread operator (...
) is used to spread the elements of sourceArray
and add them individually to targetArray
How can I push an array into another array using Vue js?
In the code, we have two arrays: array1 with values [1, 2, 3] and array2 with values [4, 5, 6]. When the button is clicked, the pushArray method is triggered. Inside this method, the spread operator (…) is used to push the elements of array2 into array1. So, after the pushArray method is executed, array1 will become [1, 2, 3, 4, 5, 6].
The result variable is then updated with the value of array1, and it is displayed in the HTML template as the “Result” paragraph.
Vue Js Push Array to Array Example
<div id="app">
<p>Array 1: {{ array1 }}</p>
<p>Array 2: {{ array2 }}</p>
<button @click="pushArray">Push Array 2 into Array 1</button>
<p>Result: {{ result }}</p>
</div>
<script type="module">
const app = new Vue({
el: "#app",
data: {
array1: [1, 2, 3],
array2: [4, 5, 6],
result: null
},
methods: {
pushArray() {
this.array1.push(...this.array2);
this.result = this.array1;
}
}
});
</script>