Vue Js slice() function: Slice() creates a new array from a subset of an array’s elements. The slice() method makes choices between a specified start and a specified (but non-exclusive) end. The original array does not modified when using the slice() method.In this tutorial, we will demonstrate how to use the array slice method in Vue.js to copy the selected area of an array and save it into a new array.
How to use javascript slice method in Vue Js?
The JavaScript String slice() in the Vue.js method will be demonstrated in this example.
Vue Js slice Array function | Example
<div id="app">
<button @click="myFunction">click me</button>
<p>{{array}}</p>
<p>New array: {{results}}</p>
</div>
<script type="module">
import { createApp } from 'vue'
createApp({
data()
{
return{
array:['Font Awesome Icons','Sarkari Naukri Exams','Tutorials Plane','School Geeks Technology'],
results:''
}
},
methods:{
myFunction(){
this.results = this.array.slice(1,3);
},
}
}).mount('#app')
</script>
Using Slice string in Vue.js example
returns a fresh string containing the string’s portion that was extracted.
Vue js slice string | Example
<div id="app">
<button @click="myFunction">click me</button>
<p>{{demoString}}</p>
<p>Slice string: {{results}}</p>
</div>
<script type="module">
import { createApp } from 'vue'
createApp({
data()
{
return{
demoString:'fontawesomeicons',
results:''
}
},
methods:{
myFunction(){
this.results = this.demoString.slice(1,6);
},
}
}).mount('#app')
</script>
Output of above Example
Vue.js slice() method when the indices are negative
The values are counted backward if startingIndex or endIndex are both negative. For example in the case, -1 denotes the final element, -2, the next-to-last element, and so on.
Vue js slice: array with negative arguments | Example
<div id="app">
<button @click="myFunction">click me</button>
<p>{{demoArray}}</p>
<p>New Array: {{results}}</p>
</div>
<script type="module">
import { createApp } from 'vue'
createApp({
data()
{
return{
demoArray:['a','b','c','d','e','f','g','h'],
results:''
}
},
methods:{
myFunction(){
this.results = this.demoArray.slice(-7,-4);
},
}
}).mount('#app')
</script>