如何在 Vue 中使用過濾器向陣列新增元素?
Vue 可以定義為一個用於構建使用者介面的漸進式框架。它有多個指令,可以根據使用者的需求使用。核心庫主要專注於構建檢視層,並且也很容易選擇其他庫或與之整合。
在下面的文章中,我們將瞭解如何向陣列新增元素。陣列基本上是元素的集合。這種向陣列中新增元素的過程可以在現實生活中用於不同的場景。例如:它可以用於建立購物清單、向列表中新增員工等等。
我們可以透過使用 Vue 中的 v-for 指令來實現上述功能。我們可以遍歷當前陣列,複製所有元素,然後將新元素新增到新陣列中。
語法
以下是使用 Vue 迴圈 (v-for 指令) 呼叫過濾器的語法
$options.filters.addLast(data, other_parameters)
示例:向陣列新增元素
將下面的程式碼片段複製貼上到你的 Vue 專案中並執行 Vue 專案。你將在瀏覽器視窗中看到以下輸出。
檔名 - app.js
目錄結構 -- $project/public -- app.js
// Adding elements to the below list
const parent = new Vue({
el: '#parent',
data: {
arr1: ['Mike', 'John', 'Elena', 'Nick']
},
filters: {
addLast: function (arr, item_arr) {
// Using the spread syntax to add the
// items to the end of the array
const final_list = [...arr, ...item_arr]
return final_list
}
}
})
檔名 - index.html
目錄結構 -- $project/public -- index.html
<javascript>
<head>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script></script>
</head>
<body>
<div id='parent'>
<p>
<strong>Current List : </strong>
<ol>
<li v-for='item in arr1'>
<strong>{{item}}</strong>
</li>
</ol>
<strong>Final List : </strong>
<ol>
<li v-for='item in $options.filters.addLast(arr1, ["Bill","Steve","Rachel"])'>
<strong>{{ item }}</strong>
</li>
</ol>
</p>
</div>
<script src='app.js'></script>
</body>
</javascript>
執行以下命令以獲取以下輸出 -
C://my-project/ > npm run serve
完整程式
以下是使用以上兩個程式碼片段(app.js 和 index.html)建立的完整程式碼。現在您可以輕鬆地將以下程式作為 javascript 檔案執行。
<javascript>
<head>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script></script>
</head>
<body>
<div id='parent'>
<p>
<strong>Current List : </strong>
<ol>
<li v-for='item in arr1'>
<strong>{{item}}</strong>
</li>
</ol>
<strong>Final List : </strong>
<ol>
<li v-for=' item in $options.filters.addLast(arr1, ["Bill","Steve","Rachel"])'>
<strong>{{ item }}</strong>
</li>
</ol>
</p>
</div>
<script>
// Adding elements to the below list
const parent = new Vue({
el: '#parent',
data: {
arr1: ['Mike', 'John', 'Elena', 'Nick']
},
filters: {
addLast: function (arr, item_arr) {
// Using the spread syntax to add the
// items to the end of the array
const final_list = [...arr, ...item_arr]
return final_list
}
}
})
</script>
</body>
</javascript>
在這裡,我們演示瞭如何根據資料和/或 Vue.js 中的過濾器的更改,輕鬆且動態地向陣列新增元素。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP